• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Diference between SQL "UPDATE" query and Session.saveorUpdate()

 
Vamsi Mohan Pemmaraju
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

In hibernate updation of data is done using session.save() or session.saveOrUpdate().

In addition in Hibernate there is a provision for executing queries explicitly using session.createQuery().

After using session.saveOrUpdate() or the other method I found hibernate executing a select query and then a update or delete query.

Which method is preferred? I suppose the first way will be causing an overhead to the DB.

regards,
Vamsi Mohan
 
Mark Spritzler
ranger
Sheriff
Posts: 17278
6
IntelliJ IDE Mac Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Simply put, if you use createSQLQuery and write the query yourself, then your code will have to determine whether you need an update statement or an insert statement, it will also not do anything to your related objects within the main object, you will have to manually go through any Collections within the object, and like the main object, determine if you need an insert/update or delete statement, etc. Also, you will have no idea if you have a stale object, which means you will probably want to go to the database first and see if it is stale. So basically you have to do tons of work manually yourself, if you want that control.

With saveOrUpdate method Hibernate will determine whether it needs an insert or update statement, Hibernate will do transitive persistence to your Collections, if you use the corresponding cascade-option. And if you have optimistic locking then it will also do a select for you before the update to determine if you have stale data or not.

So, I'd say for a complex graph of objects, that you are looking at 15 minutes of coding, versus 2-3 days of coding and also easier to maintain and fix bugs because you will a ton less code using saveOrUpdate().

I hope that helps.

Mark
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic