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.
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.
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.
In JPA, we can easily insert data into database through entities. The EntityManager provides persist() method to insert records.
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.
You can do it using NativeQuery and its executeUpdate method:
String query = "insert into Employee values(1,?)";
em.createNativeQuery(query)
.setParameter(1, "Tom")
.executeUpdate();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With