【发布时间】:2020-12-15 10:53:04
【问题描述】:
我有一个具有这种关系的表:
parent
| \
child1 child1
/ \
grandchild1 grandchild2
我打电话给孙子、孩子和父母只是为了说明问题。不是继承问题
@Entity
@Table(name = “parent")
@Data
@EqualsAndHashCode(callSuper = true, exclude = { “..." })
@ToString(exclude = { “..." })
@NoArgsConstructor
public class Parent {
private static final long serialVersionUID = 1L;
@OneToMany(mappedBy = “parent")
@Cascade({org.hibernate.annotations.CascadeType.ALL})
private Set<Child> children;
}
子.java
@Entity
@Table(name = “child")
@Data
@EqualsAndHashCode(callSuper = true)
@NoArgsConstructor
public class Child {
private static final long serialVersionUID = 1L;
@ManyToOne
@JoinColumn(name = “parent_id")
private Parent parent;
@OneToMany(mappedBy = “child")
@Cascade({org.hibernate.annotations.CascadeType.ALL})
@LazyCollection(LazyCollectionOption.FALSE)
private List<Grandchild> grandchildren = new ArrayList<>();
}
我正在尝试使用 CascadeType.ALL 直接删除父级,我没有发现任何问题。但是当我尝试删除时,我得到了:
08-26 11:36:33,755 错误 [SqlExceptionHelper] 无法删除或更新 父行:外键约束失败(
database.child, 约束FK_abcdefg12345外键 (parent_id) 参考parent_id(id)) 2020-08-26 11:36:33,773 信息 [AbstractBatchImpl ] HHH000010:在批处理发布时,它仍然包含 JDBC 语句 2020 年 8 月 26 日 11:36:33.776 警告 [http-nio-8080-exec-6] com.sun.faces.lifecycle.InvokeApplicationPhase.execute #{delete()}: org.springframework.dao.DataIntegrityViolationException:不能 执行语句; SQL [不适用];约束[空];嵌套异常是 org.hibernate.exception.ConstraintViolationException:不能 执行语句
我认为从 JPA 导入 CascadeType 而不是从 org.hibernate 导入 CascadeType 可能是一个错误。我也试过只使用 JPA 代码,例如 @OneToMany(mappedBy = "parent", orphanRemoval = true, cascade = CascadeType.ALL),但没有用。
代码
parent.setChildren(null);
parentRepository.delete(parent); //throws the exception
依赖关系
- Spring Data JPA 1.7.0
- 休眠 4.2.1.Final
- Spring 集成 JDBC 2.2.6
- Spring 集成 JPA 2.2.6
我做错了什么?
【问题讨论】:
-
当您遇到问题时,直接删除子或孙?
-
@DineshDontha 当我尝试删除父母及其子女时会发生这种情况