Reputation: 1301
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.
Upvotes: 22
Views: 117201
Reputation: 50
String query = "SELECT * FROM daily_clouser_report_summery b "
+ "WHERE operatorId='" + operatorId + "' AND "
+ "STR_TO_DATE(b.repDate, '%d-%m-%Y')"
+ "BETWEEN STR_TO_DATE('" + formattedDates + "', '%d-%m-%Y') AND STR_TO_DATE('" + formattedDates + "', '%d-%m-%Y');";
SessionFactory sf = this.hibernateTemplate.getSessionFactory();
EntityManager em = sf.createEntityManager();
List<DailyClouserReportSummery> list = em.createNativeQuery(query, DailyClouserReportSummery.class).getResultList();
return list;
Upvotes: 0
Reputation: 61
You can use createNativeQuery
to write a query specific to the database language.
String query = "INSERT INTO userinfo ( login, upassword, email, mobile, fax, dob)"
+ " VALUES ( :a, :b, :c, :d, :e, :f)"
em.createNativeQuery(query)
.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();
Upvotes: 6
Reputation: 10180
You can do it using NativeQuery and its executeUpdate method:
String query = "insert into Employee values(1,?)";
em.createNativeQuery(query)
.setParameter(1, "Tom")
.executeUpdate();
Upvotes: 15
Reputation: 4517
I had same problem. Here is solution.
EntityManager em = getEntityManager();
EntityTransaction et = em.getTransaction();
et.begin();
em.createNativeQuery("UPDATE ... ;").executeUpdate();
et.commit();
Upvotes: 9
Reputation: 8323
Assuming you're using the container-managed entityManager
(injected with @PersistenceContext
) you just miss an @Transactionnal
annotation above your TestFacade method.
Upvotes: 5