Insert into my JPA using custom entity management request

I am trying to insert data into my database, I am using JPA in my project.

This is what my bean looks like.

@PersistenceContext EntityManager em; em.createNativeQuery("INSERT INTO testtable ('column1','column2') VALUES ('test1','test2')").executeUpdate(); 

myfacade:

 @Stateless public class TestFacade extends AbstractFacade<Test> { @PersistenceContext(unitName = "TEST2PU") private EntityManager em; @Override protected EntityManager getEntityManager() { return em; } public TestFacade() { super(Test.class); } 

I get an error message:

 javax.persistence.TransactionRequiredException: executeUpdate is not supported for a Query object obtained through non-transactional access of a container-managed transactional EntityManager 

and if I do not use @PersistenceContext for EntityManager

 EntityManagerFactory emf = Persistence.createEntityManagerFactory("TEST2PU"); EntityManager em = emf.createEntityManager(); em.createNativeQuery("INSERT INTO testtable ('column1','column2') VALUES ('test1','test2')").executeUpdate(); 

this is my mistake:

 javax.persistence.TransactionRequiredException: Exception Description: No externally managed transaction is currently active for this thread 

note: you really need to use your own query for this.

+7
source share
4 answers

I had the same problem. Here is the solution.

 EntityManager em = getEntityManager(); EntityTransaction et = em.getTransaction(); et.begin(); em.createNativeQuery("UPDATE ... ;").executeUpdate(); et.commit(); 
+7
source

You can do this using NativeQuery and the executeUpdate method:

 String query = "insert into Employee values(1,?)"; em.createNativeQuery(query) .setParameter(1, "Tom") .executeUpdate(); 
+7
source

Assuming you are using a container- entityManager (introduced with @PersistenceContext ), you simply skip the @Transactionnal annotation over your TestFacade method.

+2
source
  String message = ""; try { EntityManager em = emf.createEntityManager(); if (objUser.getId() <= 0) { em.getTransaction().begin(); em.createNativeQuery("INSERT INTO userinfo ( login, upassword, email, mobile, fax, dob)" + " VALUES ( :a, :b, :c, :d, :e, :f)") .setParameter("a", objUser.getLogin()) .setParameter("b", objUser.getUpassword()) .setParameter("c", objUser.getEmail()) .setParameter("d", objUser.getMobile()) .setParameter("e", objUser.getFax()) .setParameter("f", objUser.getDob()).executeUpdate(); em.getTransaction().commit(); em.close(); message = "Success"; } } catch (HibernateException ex) { message = ex.getMessage(); } 
0
source

All Articles