Only makes sense if your use assigned id's and in that case they should actually be generated.
What is an assigned id?
Maybe I am going the wrong way, but I explain what I try to do: I persist an new entity which has a child entity (many-to-one relationship). The entity has a foreign key of the child, but the child is not updated and already exists. The entity class has a field of type child entity.
So I want to set the foreign key easily by
ChildEntity c = new ChildEntity();
3 lines instead of 1!
I don't need to set the other fields of the child entity as it is not persisted.
assigned id is when you do not have autogenerated keys.
entity.setChild(new ChildEntity(childId)) is rather bad since why do you want to have an incomplete objectgraph?
better approach is:
That will do the same thing and wont load the childentity unless you try to access methods on it avoiding incomplete objectgraph.
I see, thanks.
By "session.load()" do you mean EntityManager.find()? Or of which class is your session object?
I don't have auto-generated IDs, but the constructor(id) is not generated. Anyway, if your approach is better, I'll use that.
em.find(Your.class, id) will work too.