Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

differences between native query and jpql query  RSS feed

 
carlo sciandrone
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi I've noticed a strange behaviour using jpql queries vs native queries.
I hava a situation like this (the above are two ejb methods):

@Override

public void updateForTestJPQL() {

Persona cust = em.find(Persona.class, 1);

cust.setCognome("bianchi");

Query q = em.createQuery( "UPDATE Persona p SET p.cognome = 'gialli'");



q.executeUpdate();

System.out.println(cust.getCognome());



}

@Override

public void updateForTestNative(){

Persona cust = em.find(Persona.class, 1);

cust.setCognome("bianchi");

Query q=em.createNativeQuery("UPDATE persona p SET p.cognome = 'gialli'");

q.executeUpdate();

System.out.println(cust.getCognome());



}

When I call the updateForTestJPQL I see that after execution all records have been updated on the DB table with the value "gialli".
When I call the updateForTestNative after execution I have all the records updated except the first one, which has the value of "bianchi" ?
Can anyone explain me why?
Thanks a lot!!!
 
Joemon Anthony
Greenhorn
Posts: 26
Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
With JPA, what ever chances you do, that happens in the persistence context area. When the service(the method which you have called) ends, at that time all the contents of the persistence context area is flushed into the database.

1. For service updateForTestJPQL: - Whatever things you are doing is part of JPQL(JPA), and the data from persistence context will be flushed only at the end of service call. That is the reason why all the records in the database are having the same value "gialli".

2. For service updateForTestNative: - In this service you are using native Query, so the updation in the database will occur at the time itself, when you call the executeUpdate. and finally when the service ends the data in the persistence context gets flushed. That means, with native query update, all the records will be updated with value "gialli", but when finally the service ends the persistence context data will be flushed and entered into database, thats why you are getting one record with value "bianchi"

 
Joemon Anthony
Greenhorn
Posts: 26
Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hope you understood.
 
carlo sciandrone
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you very mutch, now it's perfectly clear!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!