【发布时间】:2017-03-09 13:16:33
【问题描述】:
我使用容器管理的 JPA 来注入 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)
【问题讨论】:
-
为什么不用spring提供的Transaction。
-
"@VibhaySachan 我们没有在工作场所使用 spring。使用 wildfly 10 休眠。
-
那么你可以使用 javax.transaction.Transactional
-
@VibhaySachan “Transactional”和“TransactionAttribute()”注解有什么区别?我使用“TransactionAtrribute”注释。还不够吗?
标签: hibernate wildfly entitymanager jta