Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Devaka Cooray
  • Knute Snortum
  • Paul Clapham
  • Tim Cooke
Sheriffs:
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Bear Bibeault
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Ron McLeod
  • Piet Souris
  • Frits Walraven
Bartenders:
  • Ganesh Patekar
  • Tim Holloway
  • salvin francis

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

 
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
 
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.
 
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
Boost this thread!