How to get the id of an object that is being cascaded with JPA

If you have a regular Foo object and persistent (foo), @Id is automatically set to the entity. However, if the mentioned Foo object has a set of bars associated with it via

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

      

and such an instance is already saved if you create a new Bar and add it to the Bars collection foo and call merge (foo) the newly created Bar is saved but its @Id is not updated!

Is there a way to get this ID without making a later lookup call (Foo.class, foo.getId ())?

+1


source to share


1 answer


The call to merge () will not update the passed objects. However, it will return updated objects.

From the Hibernate docs:

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



and merge () are very different:

  • if there is a persistent instance with the same ID currently associated with the session, copy the state of the given object into the persistent instance
  • If the session does not have a persistent instance, try loading it from the database or creating a new persistent instance
  • a persistent instance is returned
  • this instance is not associated with the session, it remains disconnected
0


source







All Articles