Inserting in my JPA using entity manager native query

galao picture galao · May 29, 2013 · Viewed 76.6k times · Source

I am trying to insert a data in 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:

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 dont 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 error:

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

note: really need to use native query for this.

Answer

Saeed Zarinfam picture Saeed Zarinfam · Sep 13, 2014

You can do it using NativeQuery and its executeUpdate method:

String query = "insert into Employee values(1,?)";

em.createNativeQuery(query)
   .setParameter(1, "Tom")
   .executeUpdate();