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?
This is the error I get:
java.lang.IllegalStateException:
Exception Description: Cannot use an EntityTransaction while using JTA.
Here is the code that I use:
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;
}
}
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.
Try this:
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;
}
}