以下代码为我提供了org.hibernate.HibernateException: The internal connection pool has reached its maximum size and no connection is currently available!.
此错误表明我没有关闭事务,因为我将connection pool
大小设置为20,所以在消耗所有连接时会出错。以下是代码:
public class XxspAsnOutHeaderRepo {
public static Logger logger = Logger.getLogger(XxspAsnOutHeaderRepo.class);
private EntityManager entityManager = JPAUtil.getEntityManagerFactory().createEntityManager();
private EntityTransaction transaction = entityManager.getTransaction();
public List<XxspAsnOutHeaderEntity> getOneOutHeaderWithFlag(String flag) {
TypedQuery<XxspAsnOutHeaderEntity> query = null;
try {
if (!transaction.isActive())
transaction.begin();
logger.info("getting headers from Database..... ");
query = entityManager.createNamedQuery(XxspAsnOutHeaderEntity.FIND_ALL_HEADERS_FLAG_SIX, XxspAsnOutHeaderEntity.class)
.setParameter("proc_flag", flag).setMaxResults(1);
} catch (PersistenceException ex) {
logger.error("Error occured while fetching data from DataBase...\n", ex);
throw ex;
} finally {
if (transaction.getRollbackOnly())
transaction.rollback();
}
return query.getResultList();
}
}
测试用例:
@Test
public void testConnectionPoolLimit(){
for(int i=1; i<30; i++){
new XxspAsnOutHeaderRepo().getOneOutHeaderWithFlag("6");
}
}
上述代码在20 select
个语句后失败。但是当我删除if (!transaction.isActive()) transaction.begin();
时,代码运行正常并创建了30个读取操作。而这一次提高了速度
如果我最后写transaction.commit();
语句,上面也会运行。但表现很慢。
Read
操作不需要交易吗?