ITeye博客

hibernate中取得connection的方法

yang7527 · 2012-07-01 16:55 · 企业架构 · Markdown

在hibernate3中,使用了c3p0连接池,尝试了多种办法取得connection对象,以下两种可以使用。

Java代码 复制代码 收藏代码

  1. Connection conn;
  2. // 方法1:hibernate4中将要废弃这个方法
  3. conn = session.connection();
  4. // 方法2:这个方法也可以用,速度稍慢
  5. SessionFactoryImplementor sessionFactory = (SessionFactoryImplementor)new Configuration().configure().buildSessionFactory();
  6. conn = sessionFactory.getConnectionProvider().getConnection();
  7. //方法:3
  8. ConnectionProvider cp =((SessionFactoryImplementor)sessionFactory).getConnectionProvider();
  9. cp.getConnection();
Connection conn;

// 方法1:hibernate4中将要废弃这个方法
conn = session.connection();

// 方法2:这个方法也可以用,速度稍慢
SessionFactoryImplementor sessionFactory = (SessionFactoryImplementor)new Configuration().configure().buildSessionFactory(); 
conn = sessionFactory.getConnectionProvider().getConnection();

//方法:3
ConnectionProvider cp =((SessionFactoryImplementor)sessionFactory).getConnectionProvider();
cp.getConnection();

2012/06/25
http://zhidao.baidu.com/question/170727565.html
按hibernate的计划,4.0开始将除去Session.connection()这个方法,所以还是最好不要使用它了。
官方的替代方法是用Session.doWork();
如:

Java代码 复制代码 收藏代码

  1. getSession().doWork(
  2. new Work() {
  3. public void execute(Connection connection) {
  4. // 这里已经得到connection了,可以继续你的JDBC代码。
  5. // 注意不要close了这个connection。
  6. }
  7. }
  8. );

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。