IllegalStateException:使用JTA时无法使用EntityTransaction [英] IllegalStateException: Cannot use an EntityTransaction while using JTA
问题描述
我正在使用JPA为学校做一个项目.我正在尝试保留一个对象,但出现了我无法修复的错误.我已经读到我必须使用usertransaction而不是entitytransaction,但是在本课程中我们没有得到太多信息,所以我对该主题了解不多.我该如何解决该错误并能够保留该错误?
I'm making a project for school using JPA. I'm trying to persist an object but I'm getting an error I can't fix. I've read that I have to use usertransaction instead of entitytransaction but we didn't get much information during this lesson so I don't know a lot about this topic. How can I fix this error and be able to persist it?
这是我得到的错误:
java.lang.IllegalStateException:
Exception Description: Cannot use an EntityTransaction while using JTA.
这是我使用的代码:
public class UserServiceImpl implements UserService {
@PersistenceUnit
private EntityManagerFactory emf = null;
private EntityManager em = null;
@Override
public User register(User user) {
emf = Persistence.createEntityManagerFactory("Project_JavaPU");
em = emf.createEntityManager();
em.getTransaction().begin();
em.persist(user);
em.flush();
em.getTransaction().commit();
em.close();
return user;
}
}
推荐答案
我建议将无状态EJB与容器管理的实体管理器一起使用,以进行JTA处理的事务.请参见 Java EE 6教程中的本节
容器管理只是比更复杂的应用程序管理方式更容易选择的方式,除非您有充分的理由.
I suggest to use a stateless EJB with a container-managed entity manager for transaction to be taken care of by JTA. See this Section in Java EE 6-Tutorial
Container-managed is just the easy way that is to be chosen over the more complex application-managed way except you have good reasons to do so.
尝试一下:
package containing.package;
import package.of.your.UserService
import java.io.Serializable;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
@Stateless
public class UserServiceImpl implements UserService, Serializable {
@PersistenceContext
EntityManager em;
@Override
public User register(User user) {
em.persist(user);
return user;
}
}
这篇关于IllegalStateException:使用JTA时无法使用EntityTransaction的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!