java Hibernate在更新现有父实体时不创建新的子实体
我有一对多的基数关系,如下所示:
@Entity
@Table(name = "PARENT_TABLE")
public class Parent {
@Id
@GeneratedValue(generator = "uuid2")
@GenericGenerator(name = "uuid2", strategy = "uuid2")
@Column(name = "PARENT_ID", updatable = false, nullable = false, length = 16)
@Type(type="uuid-binary")
private UUID id;
private String parentName;
@OneToMany(fetch=FetchType.LAZY, mappedBy = "parent", cascade = CascadeType.ALL, orphanRemoval = true)
@JoinColumn(name="PARENT_ID")
private List<Child> children;
}
@Entity
@Table(name = "CHILD_TABLE")
public class Child {
@Id
@GeneratedValue(generator = "uuid2")
@GenericGenerator(name = "uuid2", strategy = "uuid2")
@Column(name = "CHILD_ID", updatable = false, nullable = false, length = 16)
@Type(type="uuid-binary")
private UUID id;
private String childName;
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name = "PARENT_ID", referencedColumnName = "PARENT_ID")
private Parent parent;
}
现在,我已经有了一个有两个孩子的家长,我有一个更新家长的电话,它正在更新家长中的一些信息,并在家长中添加一个孩子
List<Child> existingChild = getFromDbByParent(parent);
existingChild.add(new Child());
hibernateTemplate.update(parent);
//hibernateTemplate.saveOrUpdate(parent);
上面的代码失败了,因为对于第三个孩子,hibernate在保存到DB时没有创建ID。所以,我犯了一个错误
2019-12-19 13:02:04.589 DEBUG SqlExceptionHelper io-12347-exec-1 could not execute batch [update CHILD_TABLE set CHILD_ID =null where PARENT_ID=?]
java.sql.BatchUpdateException: ORA-01407: cannot update ("DB"."CHILD_TABLE"."CHILD_ID") to NULL
创建父对象和新的子对象效果很好,即使使用JPA级联注释也是如此。这里能做什么
注意:这是一个从repo层迁移到hibernate的项目,所以我试图避免逻辑上的变化,这就是为什么要在现有父级中保存新的子级。我知道,最好先给孩子打电话
共 (0) 个答案