我使用容器管理的JPA注入EntityManager实例。使用注入的entitymanager实例,当我使用find()方法时,它表示实体管理器已关闭。 我使用wildfly 10。
我如何克服这个问题?我在这里做错了什么?
我像这样创建实体经理;
@PersistenceContext
protected EntityManager em;
@Stateless
public class CustomerService CrudService<Customer> {
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void update(Customer entity) {
Customer item = em.find(Customer.class,entity.getId()); //ISSUE
if (entity.getParentId()!=null) {
item.setParent(em.find(CRMEntity.class , entity.getParentId()));
item.setParentId(entity.getParentId());
}
....
super.update(item);
}
public abstract class CrudService<T extends BaseEntity> {
public void update(T entity) {
Session session = null;
try {
session = getSession();
session.update(entity);
session.flush();
} catch (HibernateException ex) {
log.error("Error when update." + entity.getCode(), ex);
if (session != null) {
session.cancelQuery();
}
} finally {
if (session != null && session.isOpen()) {
session.clear();
session.close();
}
}
}
public Session getSession() {
if (session == null || !session.isOpen()) {
session = getEntityManager().unwrap(Session.class);
}
return session;
}
}
我在这一行遇到问题;
Customer item = em.find(Customer.class,entity.getId());
错误
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.find(SessionImpl.java:3312)
at org.hibernate.internal.SessionImpl.find(SessionImpl.java:3297)
at org.jboss.as.jpa.container.AbstractEntityManager.find(AbstractEntityManager.java:213)
at com.leightonobrien.lob2.service.autogen.CustomerService.update(CustomerService.java:412)
at sun.reflect.GeneratedMethodAccessor249.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.jboss.as.ee.component.ManagedReferenceMethodInterceptor.processInvocation(ManagedReferenceMethodInterceptor.java:52)
at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
at org.jboss.invocation.InterceptorContext$Invocation.proceed(InterceptorContext.java:437)
答案 0 :(得分:1)
这里的问题是我关闭了会话。删除后,一切正常