Say I have a User and UserProfile entities. I’d like to be able to create a User u, save/attach it to the Hibernate context, then simply call, e.g., u.getUserProfile().setFirstName("Steve") without having to instantiate and set the UserProfile object.
For clarity, here’s some code:
// create, populate, and save user with only some primitive values
// note that no UserProfile is explicitly set
User u = new User();
u.setSomePrimitive(somePrimitive);
u.setSomeOtherPrimitive(someOtherPrimitive);
session.save(u);
// navigate into and set something on the user profile
u.getUserProfile().setFirstName("Steve-o");
Basically, I want Hibernate to lazily instantiate associations of attached entities for me. I figure that Hibernate could very easily mark as dirty and persist only those lazily created associations that have data set to them, otherwise ignore.
Is this possible?
No, it’s not (and it’s a good thing!). BTW, it would only make sense for a one-to-one, mandatory association. And you would have to fill the profile with all its mandatory values before saving the user anyway. What’s so difficult about
new UserProfile()?If you want to do that, you can create the profile in the constructor of User, and set a cascade so that the profile is saved when the user is.