可以同时使用Hibernate和Tomcat连接池吗?

Am1*_*3zA 5 java hibernate jdbc

我正在开发一个java Web应用程序,我使用Tomcat连接池,这是我的设置:

<?xml version="1.0" encoding="UTF-8"?>
<Context path="" docBase="" debug="5" reloadable="true" crossContext="true">
<Resource name="jdbc/jdbcPool"
            auth="Container"
            type="javax.sql.DataSource"
            maxActive="100"
            maxIdle="30"
            maxWait="10000"
            username="root"
            password="*******"
            driverClassName="com.mysql.jdbc.Driver"
            url="jdbc:mysql://localhost:3306/dbname?autoReconnect=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>            
</Context>
Run Code Online (Sandbox Code Playgroud)

和我的DAO:

 public static Connection dbConnection() throws NamingException {
        Context initContext;
        DataSource ds = null;
        Connection conn = null;
        try {
            initContext = new InitialContext();
            Context envContext = (Context) initContext.lookup("java:/comp/env");
            ds = (DataSource) envContext.lookup("jdbc/jdbcPool");
            conn = ds.getConnection();        
        }catch (SQLException ex){
            logger.error("SQLException Occurred in DAO.dbConnection() Method, Exception Message is: " + ex.getMessage(), ex);
        }
        catch (RuntimeException er){
            logger.fatal("SQLException Occurred in DAO.dbConnection() Method, Exception Message is: " + er.getMessage(), er);
        }catch(Exception rt){
           logger.fatal("Exception Occurred in DAO.dbConnection() Method, Exception Message is: " + er.getMessage(), er);
        }
        return conn;
    }
Run Code Online (Sandbox Code Playgroud)

我想使用hibernate,所以我重构了我的代码的一部分,现在我想知道我可能在我的应用程序中使用它们(我的意思是我的代码的某些部分使用hibernate而某些部分使用我的DAO连接?如果是的话,那些没有用hibernate映射的表会发生什么,但是一些映射表与它们有关系?

Gar*_*vis 3

我个人对 hibernate 的偏好是根本不配置连接池。这可以通过简单地省略 hibernate 配置中的连接池设置并使用 openSession(Connection) 方法来完成:

Connection conn = ... // get from jndi
Session session = sessionFactory.openSession(connection);
try{
   //do some work with either hte connection or the session or both
}finally{
   session.close();
   conn.close();
}
Run Code Online (Sandbox Code Playgroud)

这样做的优点是您可以控制正在使用哪个连接以及在哪里分配它,最重要的是在哪里关闭它,如果您使用 hibernate 和 jdbc 代码执行事务,这可能很重要。

编辑:@ChssPly76 关于排除 hibernate 内置事务管理的观点,他是完全正确的,hibernate 提供了合理的事务支持,并且如果给定的 JTA 将与任何正在进行的事务同步。在一个非 JTA 应用程序中,您需要 hibernate 和 jdbc 代码在同一个 jdbc 事务中操作,确保 hibernate 会话使用与 jdbc 代码相同的连接非常重要,最好的方法是给出连接到会话工厂。请注意,这并不排除使用 Hibernate 事务对象:

Connection conn = ... // get from jndi
Session session = sessionFactory.openSession(connection);
try{
   Transaction tx = new Transaction(); // 
   //do some work with either hte connection or the session or both
   tx.commit();
}finally{
   session.close();
   conn.close();
}
Run Code Online (Sandbox Code Playgroud)

它会工作得很好。