• 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

saveOrUpdate () doubt

 
Ranch Hand
Posts: 10198
3
Mac PPC Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Guys,

I have a doubt on this method. Now imagine, I have a transient object (object that is not yet associated in a session) and I want to persist it, so I say obj.saveOrUpdate (). Now how will Hibernate know that the Object is not yet i n the database? I mean how can Hibernate distinguish whether to issue a update query or an insert query? Please help guys!
 
ranger
Posts: 17347
11
Mac IntelliJ IDE Spring
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
It is based on the id. Which is why you need to make sure your <id> is unique. Basically if Hibernate sees that the id is null, it knows that it is an insert

(Of course, if you use "application" for generator, this is different and because you started with a detached object, Hibernate will most likely run a Select statement looking to see if a row already exists in the database for that id)

Also look at optimistic locking and why it is always a good idea to implement your equals and hashcode methods.

Mark
 
author and cow tipper
Posts: 5009
1
Hibernate Spring Tomcat Server
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Indeed, Mark is very correct.

The Hibernate API JavaDoc provides some further information as well:



public void saveOrUpdate(Object object) throws HibernateException

Either save(Object) or update(Object) the given instance, depending upon resolution of the unsaved-value checks (see the manual for discussion of unsaved-value checking). This operation cascades to associated instances if the association is mapped with cascade="save-update".



Hibernate JavaDoc for org.hibernate.Session - saveOrUpdate

-Cameron McKenzie
 
Joe San
Ranch Hand
Posts: 10198
3
Mac PPC Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks guys!
 
reply
    Bookmark Topic Watch Topic
  • New Topic