java - 在 hibernate 中更新父对象后,子对象属性为 NULL

标签 java spring hibernate

具有以下 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/

相关文章:

java - 如何在 Eclipse for Google App Engine 中从 Java 7 切换到 Java 6?

java - 为什么我的交易不活跃? javax.persistence.TransactionRequiredException : Executing an update/delete query

java - 最终局部变量无法分配,因为它是在封闭类型中定义的

Java Future - Spring Authentication 在 AuditorAware 中为空

java - CentOS上的Spring Boot启动时间较长

java - nGrinder WAR 抛出异常

java - HTTP 状态 500 - 未能延迟初始化角色 : . 的集合 ..,无法初始化代理 - 无 session

java - 如何在Eclipse中调试外部插件?

java - Spring RestTemplate - 指定 Jackson View

java - 在镜头之间添加延迟(按键)