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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1163157/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 15:27:24  来源:igfitidea点击:

can Use Hibernate and Tomcat Connection pool at same time?

javahibernatejdbc

提问by Am1rr3zA

I am developing a java web Application and I use Tomcat connection pooling, here is my setting:

我正在开发一个 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>

and my DAO:

和我的 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;
    }

I want to use hibernate so I refactor some part of my code, now I want to know is it possible for me us use both of them in my application (I mean some part of my code use hibernate and some part use my DAO connection?) If yes, what's gonna happen to those tables that not mapped with hibernate but some mapped tables have relation with them?

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

采纳答案by Gareth Davis

My personal preference with hibernate is is not to configure it with a connection pool at all. This can be done by simply omitting the connection pool settings in our hibernate configuration and using the openSession(Connection) method:

我个人对 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();
}

This has the advantage that you are in control of which connection is being used and where it is allocated, and most importantly where it is closed, this may be important if you are performing a transaction using hibernate and jdbc code.

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

EDIT: on @ChssPly76 point about excluding hibernates inbuilt transaction management, and he is quite right, hibernate provides reasonable transaction support and if a given a JTA will synchronise with any on going transaction. In a none JTA app where you require both hibernate and jdbc code to operate in the same jdbc transaction it is important to make sure that the hibernate Session is using the same Connection as the jdbc code, the best way to do this is to give the Connection to the session factory. Note this doesn't exclude using a Hibernate transaction object:

编辑:在@ChssPly76 关于排除 hibernates 内置事务管理的观点,他是对的,hibernate 提供了合理的事务支持,如果给定的 JTA 将与任何正在进行的事务同步。在非 JTA 应用程序中,您需要 hibernate 和 jdbc 代码在同一个 jdbc 事务中运行,确保休眠会话使用与 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();
}

it'll work just fine.

它会工作得很好。

回答by ChssPly76

I suppose you can use them together, but why would you? You can configure Hibernate to use your data source instead like described in the manual. It would be something like:

我想你可以一起使用它们,但为什么要这样呢?您可以配置 Hibernate 来使用您的数据源,而不是像手册中描述的那样。它会是这样的:

hibernate.connection.datasource = java:/comp/env/jdbc/jdbcPool
hibernate.dialect = org.hibernate.dialect.MySQLDialect

As far as mappings go, "mapped" tables can have relations to "unmapped" tables (in the database), but those relations will also be "unmapped" (e.g. Hibernate won't be aware of them). So if you go that way you have to make sure you won't cause any referential integrity issues while trying to, say, insert / update "mapped" entity.

就映射而言,“映射”表可以与“未映射”表(在数据库中)有关系,但这些关系也将是“未映射”的(例如,Hibernate 不会意识到它们)。因此,如果您这样做,您必须确保在尝试插入/更新“映射”实体时不会导致任何参照完整性问题。