Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting in my JPA using entity manager native query

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.

like image 976
galao Avatar asked May 29 '13 03:05

galao


People also ask

How do you write native insert query in JPA repository?

Creating SQL Queries Add a query method to our repository interface. Annotate the query method with the @Query annotation, and specify the invoked query by setting it as the value of the @Query annotation's value attribute. Set the value of the @Query annotation's nativeQuery attribute to true.

Can we use native SQL query in JPA?

JPA has its own query language, but it's designed as a leaky abstraction and supports native SQL queries. You can create these queries in a similar way as JPQL queries, and they can even return managed entities if you want.

What is the EntityManager method to insert data?

In JPA, we can easily insert data into database through entities. The EntityManager provides persist() method to insert records.

What is the use of EntityManager in JPA?

In JPA, the EntityManager interface is used to allow applications to manage and search for entities in the relational database. The EntityManager is an API that manages the lifecycle of entity instances. An EntityManager object manages a set of entities that are defined by a persistence unit.


1 Answers

You can do it using NativeQuery and its executeUpdate method:

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

em.createNativeQuery(query)
   .setParameter(1, "Tom")
   .executeUpdate();
like image 163
Saeed Zarinfam Avatar answered Sep 22 '22 21:09

Saeed Zarinfam