具有以下 hibernate 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;
}
有以下Spring服务
@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”,因为父级是一个持久对象,并且我们处于同一个 hibernate session 中。我哪里错了?
最佳答案
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);
从数据库中检索子项,而不是手动创建它。
关于java - 在 hibernate 中更新父对象后,子对象属性为 NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48002877/