Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

saveOrUpdate () doubt

 
Joe Harry
Ranch Hand
Posts: 10128
3
Eclipse IDE Mac PPC Ubuntu
  • Mark post as helpful
  • send pies
  • 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!
 
Mark Spritzler
ranger
Sheriff
Posts: 17278
6
IntelliJ IDE Mac Spring
  • Mark post as helpful
  • send pies
  • 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
 
Cameron Wallace McKenzie
author and cow tipper
Saloon Keeper
Posts: 4968
1
Hibernate Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • 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 Harry
Ranch Hand
Posts: 10128
3
Eclipse IDE Mac PPC Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks guys!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic