文章出處

在hibernate3中,使用了c3p0連接池,嘗試了多種辦法取得connection對象,以下兩種可以使用。

Java代碼 
     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();  

 


按hibernate的計劃,4.0開始將除去Session.connection()這個方法,所以還是最好不要使用它了。
官方的替代方法是用Session.doWork();
如:

Java代碼 
         getSession().doWork(  
          new Work() {  
            public void execute(Connection connection) {  
              // 這里已經得到connection了,可以繼續你的JDBC代碼。  
              // 注意不要close了這個connection。  
            }  
          }  
        );

 

另外一個方法:

 

package com.trendcom.base.util;

import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate4.SessionFactoryUtils;
import org.springframework.web.context.ContextLoaderListener;

public class DataSourceUtil {

 private static SessionFactory sessionFactory=null;
 
 static{  
  sessionFactory=(SessionFactory) ContextLoaderListener.getCurrentWebApplicationContext().getBean("sessionFactory");
 }

 
 public static Connection getConnection(){
  try {
   return getDataSource().getConnection();
  } catch (SQLException e) {
   e.printStackTrace();
  }
  return null;
 }

 
 public static SessionFactory getSessionFactory() {
  return sessionFactory;
 }

 public static void setSessionFactory(SessionFactory sessionFactory) {
  DataSourceUtil.sessionFactory = sessionFactory;
 }


 private static DataSource getDataSource() {
  return SessionFactoryUtils.getDataSource(getSessionFactory());
 }

}

 


文章列表


不含病毒。www.avast.com
arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()