Alberto
Alberto

Reputation: 166

hibernate save associations

The hierarchy is the following: Parent object is associated with a Child object. I create a new Parent object and want to associate it with a Child object that is already stored in database and save the Parent to database. One way to do this is to preload the Child and associate it with the Parent. But can I create a new Child object, set its id, and associate it with the Parent, so when I save the Parent, hibernate will automatically find the appropriate Child and fill in missing Child fields, which are initially set to null?

Thank you.

Upvotes: 4

Views: 1687

Answers (1)

JB Nizet
JB Nizet

Reputation: 692121

No. You must get the child from the database. But if you use session.load instead of session.get, it will just initialize a proxy to the actual persistent object, without even executing a SQL query. Of course, if the entity does in fact not exist in the database, you'll have an exception at flush time (or if the entity is being fetched by some other part of the code later in the transaction).

Child child = session.load(Child.class, idOfChild); // no SQL query here
Parent p = new Parent();
p.setChild(child);
session.persist(p);

Upvotes: 6

Related Questions