tags:

views:

276

answers:

1

If one has a regular Foo entity and call persist(foo) the @Id is automatically set on the entity. However, if the said Foo entity has a collection of Bars bound to it via

(...)
@OneToMany(cascade=Cascade.ALL) 
Set<Bar> getBars()
(...)

and such instance is already persisted, if one creates a new Bar and add it to the Bars collection of foo and calls merge(foo) the Bar just created is persisted, but its @Id is not updated!

Is there a way to retrieve this id, without making a later call to find(Foo.class, foo.getId())?

A: 

A call to merge() will not update the objects that are passed in. It will however return the updated objects.

From the Hibernate docs:

http://www.hibernate.org/hib_docs/v3/reference/en/html/objectstate-saveorupdate.html

and merge() is very different:

  • if there is a persistent instance with the same identifier currently associated with the session, copy the state of the given object onto the persistent instance
  • if there is no persistent instance currently associated with the session, try to load it from the database, or create a new persistent instance
  • the persistent instance is returned
  • the given instance does not become associated with the session, it remains detached
cliff.meyers
So how can I update these objects?
What happens if you save the Foo object and then examine the instance of Foo that is returned from merge()? Do the Bar objects have their ID properties set? If not, you may need to call flush() on your EntityManager, depending on how you are handling the @Id for Bar.
cliff.meyers
Sorry, in the first sentence, I should have said "what happens if you merge the Foo object"
cliff.meyers