Reputation: 1719
Have following hibernate POJOs
@Entity
Class Parent {
long id // id, generate auto increment
Child child // many to one, eager fetch, no cascade
}
@Entity
Class Child{
long id // id, generate auto increment
String name;
}
Have following spring service
@Transactional
void myMethod() {
Parent parent = session.getParent(id); // id=10
// Here parent has child object {id: 20, name: "FirstChild"}
Child newChild = new Child(21); //DB has a child row with id 21 and name "SecondChild"
parent.setChild (newChild);
session.update(parent);
System.out.println(parent.getChild.getName())
// This print NULL
}
I expected this will print "SecondChild", as parent is a persistent object and we are in same hibernate session. Where I'm wrong ?
Upvotes: 1
Views: 525
Reputation: 57381
Parent parent = session.getParent(id); // id=10
// Here parent has child object {id: 20, name: "FirstChild"}
Child newChild = session.getChild(21);
parent.setChild(newChild);
session.update(parent);
Retrieve the child from DB rather than creating it manually.
Upvotes: 2