我正在调查我的代码中的连接泄漏。我们使用 c3p0 来管理连接池,我的一般 Hibernate 使用模式是这样的:
EntityManager entityManager = entityManagerFactory.createEntityManager();
try {
EntityTransaction transaction = entityManager.getTransaction();
transaction.begin();
//..Work involving calls to find() and merge()
transaction.commit();
} catch (... e) {
//..log message, throw nicer exceptions
} finally {
entityManager.close();
}
此代码是否有可能泄漏数据库连接?我是否必须在失败时显式回滚事务,还是自动完成? entityManager.close() 是否确保数据库连接返回到连接池中?
最佳答案
在所有 catch block 中使用 transaction.rollback()。 交易将在没有提交的情况下关闭
关于database - 正确关闭 Hibernate 事务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13590138/