【发布时间】:2017-01-29 20:58:34
【问题描述】:
我已经在 stackoverflow 上提出了类似的问题,但我无法找到正确的答案,所以如果可以的话,我会发布这个问题:
我在 Spring Boot 应用程序中有一个典型的一对多父子实体。因此,我创建了一个新子项,将其添加到父项,然后合并/刷新/清除实体管理器。子实体以新 ID 正确保存在数据库中,但父对象下的子对象 ID 为零。我错过了什么会强制刷新 ID?
创建新子代的代码位于最初获取父代的同一控制器中,因此它使用相同的 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;
}
}
孩子:
@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;
}
}
道:
@Repository
public class ParentDao {
@PersistenceContext
private EntityManager entityManager;
@Transactional
public void update(Parent parent) {
entityManager.merge(parent);
entityManager.flush();
entityManager.clear();
}
}
控制器:
@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
}
【问题讨论】: