• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to use createNativeQuery with INSERT INTO to insert data to table?

 
Peter Cong
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, in my java web apps, I used JBoss, Seam with hibernate,
I used createNativeQuery and SELECT FROM .... to get records from a DB2 table, it works well. I can get all records.
Now, after I got the records, I want to insert some of data to another table, I tried to use createNativeQuery with INSERT INTO statement, something like this:


here, codes get the list or collection from CreateNativeQuery("Select * from table1");
start to loop from the list here.
EntityManager em = emf.createEntityManager();
EntityTransaction tx = null;
try {
tx = em.getTransaction(); //I got runtime error here, it says I can not use getTransaction error,
tx.begin();

// start to insert the record something like: createNativeQuery("INSERT INTO ..... table2");
....

Could you anybody help me how to resolve this problem with some examples? thanks a lot
 
george szassy
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As far as I know, you cannot insert records via the Query interface. You can only do that with EntityManager.
 
Rafael de Sousa
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If an exception rises when you call getTransaction() method on the entity manager, you should check if you are using container manager transaction which is default when @TransactionManagement(TransactionManagementType.BEAN) is not explicitly declared.

To fire native bulk queries, try something like this, extracted from Apress - Pro JPA 2:


 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic