有以下休眠POJO
@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;
}
有以下春季服务
@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
}
我预计这将打印“SecondChild”,因为parent是一个持久对象,我们处于同一个hibernate会话中。哪里我错了?
答案 0 :(得分:2)
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);
从DB中检索子项而不是手动创建它。