我有一个EntityManager
创建的条件。
final CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
final CriteriaQuery query = criteriaBuilder.createQuery();
我将该条件存储在RestController中。
现在我喜欢在Singleton-Service中执行查询,但是我得到了一个异常:
Caused by: java.lang.IllegalStateException: Session/EntityManager is closed
at org.hibernate.internal.AbstractSharedSessionContract.checkOpen(AbstractSharedSessionContract.java:326)
at org.hibernate.engine.spi.SharedSessionContractImplementor.checkOpen(SharedSessionContractImplementor.java:126)
at org.hibernate.internal.SessionImpl.getPersistenceContext(SessionImpl.java:2234)
at org.hibernate.query.internal.AbstractProducedQuery.isReadOnly(AbstractProducedQuery.java:238)
at org.hibernate.query.internal.AbstractProducedQuery.getQueryParameters(AbstractProducedQuery.java:1249)
at org.hibernate.query.internal.AbstractProducedQuery.doList(AbstractProducedQuery.java:1404)
at org.hibernate.query.internal.AbstractProducedQuery.list(AbstractProducedQuery.java:1374)
at org.hibernate.Query.getResultList(Query.java:417)
at org.hibernate.query.criteria.internal.compile.CriteriaQueryTypeQueryAdapter.getResultList(CriteriaQueryTypeQueryAdapter.java:55)
如何将查询合并到新的EntityManager?
答案 0 :(得分:0)
为什么不懒惰地创建对象,而不是将您用一个EntityManager
创建的对象移动到另一个对象的上下文中?所以,而不是做:
final CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
final CriteriaQuery query = criteriaBuilder.createQuery();
请改为:
Function<EntityManager, CriteriaQuery> function = em -> {
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery query = criteriaBuilder.createQuery();
...
return query;
}
懒惰构造的查询将始终在正确的上下文中构建。