啊呀,初次研究这个连接池,搞了多半天,终于稍微有点眉目了。
就今天我自己总结 的认为,从连接池获取数据库连接,我的上一篇文章总结,那是没有结合Hibernate的使用。
那么,如何结合Hibernate,hibernate如何从web容器连接池获取连接呢?
步骤如下:
1.server.xml中的配置
<Context path="/myweb" docBase="myweb" debug="5" reloadable="true" crossContext="true"> <Resource name="jdbc/ds" auth="Container" type="javax.sql.DataSource" maxActive="100" maxIdle="30" maxWait="10000" username="scott" password="tiger" driverClassName="oracle.jdbc.driver.OracleDriver" url="jdbc:oracle:thin:@localhost:1521:test" /> </Context>
2.web.xml
<resource-ref> <res-ref-name>jdbc/ds</res-ref-name> <res-type>javax.sql.DataSource</res-type> <res-auth>Container</res-auth> </resource-ref>
3.hibernate.cfg.xml
<session-factory> <property name="connection.datasource">java:comp/env/jdbc/ds</property> <property name="connection.provider_class">org.hibernate.connection.DatasourceConnectionProvider</property> <property name="hibernate.show_sql">true</property> <property name="hibernate.hbm2ddl.auto">update</property> <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property> <mapping resource="pojo/User.hbm.xml" />
</session-factory>
4.
package common.util;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtils {
public static SessionFactory factory=null;
static{
Configuration cfg=new Configuration().configure("/hibernate.cfg.xml");
factory=cfg.buildSessionFactory();
}
public static SessionFactory getSessionFactory(){
return factory;
}
public static Session getSession(){
Session session=factory.openSession();
return session;
}
public static void closeSession(Session session){
if(session!=null){
if(session.isOpen()){
session.close();
}
}
}
}