我在 stackoverflow 上提出了类似的问题,但我找不到正确的答案,所以如果可以的话,我会发布这个问题:
我在 Spring Boot 应用程序中有一个典型的一对多父子实体。因此,我创建一个新的子级,将其添加到父级,然后合并/刷新/清除实体管理器。子实体已使用新 ID 正确保存在数据库中,但父对象下的子对象 ID 为零。我缺少什么会强制刷新 ID?
创建新子级的代码位于最初获取父级的同一 Controller 中,因此它使用相同的 DAO 和相同的实体管理器。
这是我的代码(实体主要由 JPA 生成):
父级:
@Entity
public class Parent implements Serializable {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
@OneToMany(mappedBy="parent", fetch=FetchType.EAGER, cascade={CascadeType.MERGE})
private List<Child> children;
public List<Child> getChildren() {
return this.Children;
}
public void setChildren(List<Child> children) {
this.children = children;
}
public Child addChild(Child child) {
getChildren().add(child);
child.setParent(this);
return child;
}
}
child :
@Entity
public class Child implements Serializable {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
@ManyToOne(cascade={CascadeType.MERGE})
@JoinColumn(name="parent_id")
private Parent parent;
public Parent getParent() {
return this.parent;
}
public void setParent(Parent parent) {
this.parent = parent;
}
}
DAO:
@Repository
public class ParentDao {
@PersistenceContext
private EntityManager entityManager;
@Transactional
public void update(Parent parent) {
entityManager.merge(parent);
entityManager.flush();
entityManager.clear();
}
}
Controller :
@Autowired
private ParentDao parentDao;
. . . createChild() {
Child child = new Child();
// Set the link on both sides of the relationship
parent.addChild(child);
parentDao.update(parent);
// --> child.getId() == 0
}
最佳答案
merge() 在新实体(在您的情况下是子实体)上调用时的工作方式是执行 persist() 调用,但有一点小小的区别。
它仅创建传递实体的副本并在该副本上调用 persist()。
因此,您的父实体无法看到 id 的更改,因为它持有子实体的“旧”实例,该实例未持久保存并最终使用新的 id 进行更新。
希望事情能够解决。
更新
要获得新状态,您需要:
1) 更改事务存储库方法以返回 merge() 值:
@Transactional
public Parent update(Parent parent) {
Parent newParent = entityManager.merge(parent);
entityManager.flush();
entityManager.clear();
return newParent
}
2)更改您的服务:
@Autowired
private ParentDao parentDao;
. . . createChild() {
Child child = new Child();
// Set the link on both sides of the relationship
parent.addChild(child);
Parent newParent = parentDao.update(parent);
// --> newParent.getChildren(0).getId() == 0
}
关于java - Hibernate:合并父级后子级 id 为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41925892/