【发布时间】:2018-03-29 00:05:18
【问题描述】:
我有两个使用 Spring 和 Hibernate 的实体
实体 A:
@Entity
@Table(name = "A")
public class A {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
@OneToOne(cascade = CascadeType.ALL, mappedBy = "a")
private B b;
这里我和实体 B 是一对一的关系,关系的所有者是实体 A。
实体 B:
@Entity
public class B{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
@OneToOne
@JoinColumn(name = "a_ID")
private A a;
保存实体没有问题。实体 B 获取数据库中实体 A 的 ID。 但是当我删除实体 A 时,我也想删除属于 A 的实体 B。
当我删除我得到错误:
MySQLIntegrityConstraintViolationException: Cannot delete or update a parent row: a foreign key constraint fails
我认为我在实体中的声明是正确的。这里有什么问题?
编辑
当我检查实体 B 的表,特别是实体 A 的外键时,它显示 Restricted on Update en on Delete
【问题讨论】:
-
您需要定义 CASCADE ON DELETE...
-
@RaymondNijland 那也不行