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

Storing and using detached objects in Hibernate

 
David Irwin
Ranch Hand
Posts: 82
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a situation that is more easily explained with the following example:

Say I create several Person objects and persist them using Hibernate and their SSN as the primary key. The Person ojbects are also cached in the actual application for future use. At this point the Person objects are now detached.

Some time later, a Team object is created and will consist of a set of Person objects. The team is populated with existing Persons from the local application cache of Persons (does not go to the database to load any Persons).

My question is this: If none of the Person objects have changed, will I get an error when trying to persist an object that consists of currently detached objects? Do I need to attach all the detached objects first?

Any clarifications would be appreciated.

Thanks.
 
Paul Croarkin
Ranch Hand
Posts: 106
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Using an SSN (or any natural key) as a primary key is a bad idea. What are you going to do if the SSN was mistyped by whoever input the data? You'll have to change it any other table that uses it as a foreign key back to your Person object.
 
David Irwin
Ranch Hand
Posts: 82
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Using an SSN (or any natural key) as a primary key is a bad idea.


This was a bad example on my part. The actual application in question uses a PK automatically generated by the database, but thanks for post.

I'm more interested in how Hibernate is going to behave in this trivial example.
 
Mark Stein
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can try using a session.saveOrUpdate. Since the generator type in the ID isn't "assigned", hibernate should be able to tell if the object is persisted or transient. What it does is look at the id field... if it's empty, it'll assume the object is transient, and do an insert. If it has a value, it'll assume it's a persisted object and do an update.

If the object is no longer in cache, I don't think hibernate will be able to tell if it's dirty or not, so it'll update even if nothing is changed.

Hope that helps.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic