public Entity saveOrUpdate(Entity entity, User u) {
EntityTransaction tx = EntityManagerHelper.getEntityManager().getTransaction();
try {
if(!tx.isActive())
tx.begin();
Entity result = null;
if (getID(entity) == null) {
EntityManagerHelper.getEntityManager().persist(entity);
} else {
result = EntityManagerHelper.getEntityManager().merge(entity);
}
tx.commit();
return result;
} catch (RuntimeException re) {
re.printStackTrace();
tx.rollback();
throw re;
}
}
正在加载对象:
@SuppressWarnings("unchecked")
public List<Entity> findByProperty(String propertyName, final Object value,
final int... rowStartIdxAndCount) {
try {
final String queryString = "select model from " + clazz.getName()
+ " model where model." + propertyName + "= :propertyValue";
Query query = EntityManagerHelper.getEntityManager().createQuery(
queryString);
query.setParameter("propertyValue", value);
if (rowStartIdxAndCount != null && rowStartIdxAndCount.length > 0) {
int rowStartIdx = Math.max(0, rowStartIdxAndCount[0]);
if (rowStartIdx > 0) {
query.setFirstResult(rowStartIdx);
}
if (rowStartIdxAndCount.length > 1) {
int rowCount = Math.max(0, rowStartIdxAndCount[1]);
if (rowCount > 0) {
query.setMaxResults(rowCount);
}
}
}
final List<Entity> result = query.getResultList();
return result;
} catch (RuntimeException re) {
re.printStackTrace();
throw re;
}
}
创建EntityManagerFactory和获取EntityManager:
private static EntityManagerFactory emf;
private static final ThreadLocal<EntityManager> threadLocal = new ThreadLocal<EntityManager>();
public static EntityManager getEntityManager() throws HibernateException {
EntityManager session = (EntityManager) threadLocal.get();
if (session == null || !session.isOpen()) {
session = (emf != null) ? emf.createEntityManager()
: null;
threadLocal.set(session);
}
return session;
}
问题在于,有时数据库连接会停留在“空闲事务”状态,并且此连接永远不会返回。几天后,应用程序因连接数超过池最大大小而停止响应。
当启用 hibernate.connection.autocommit 时,这些连接不会变成“空闲事务”,但它们仍然被阻塞,导致的问题是相同的。
我们做错了什么(缺少配置等)吗?
我注意到当我只使用急切加载时,就没有问题。但由于性能原因,我必须使用延迟加载。EntityManagerFactory 应该明确关闭吗?我希望不是,因为我们需要长时间运行应用程序,我怀疑当某人正在处理持久对象时,我不能重置它。
在日志中,我看到以下内容,但我不知道它是否与我们的问题有关:
java.lang.Exception: DEBUG -- CLOSE BY CLIENT STACK TRACE
at com.mchange.v2.c3p0.impl.NewPooledConnection.close(NewPooledConnection.java:491)
at com.mchange.v2.c3p0.impl.NewPooledConnection.close(NewPooledConnection.java:191)
at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool$1PooledConnectionResourcePoolManager.dest royResource(C3P0PooledConnectionPool.java:470)
at com.mchange.v2.resourcepool.BasicResourcePool$1DestroyResourceTask.run(BasicResourcePool.ja va:964)
at com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread.run(ThreadPoolAsynchronousRunn er.java:547)
感谢任何帮助! :)
我尝试将Hibernate的release_mode设置为“auto”,但是它没有任何效果。 - user2858263