java - 使用@ElementCollection 对实体进行级联删除
问题描述
级联删除我的父实体时遇到问题:
org.postgresql.util.PSQLException:表“child”上的 UPDATE 或 DELETE 违反约束“XXX”:对于键 (id)=(4),表“child_properties”中有引用
@Entity
@Table(name = "Parent")
public class Parent{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@OneToMany(fetch = FetchType.EAGER,mappedBy = "parent")
@OnDelete(action = OnDeleteAction.CASCADE)
private Set<Child> children;
}
@Entity
@Table(name = "child")
public class Child{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne
@JoinColumn(name = "parent_id")
private Parent parent;
@ElementCollection(fetch = FetchType.EAGER)
private Map<String,String> properties;
}
我希望孩子删除它在 parentRepository.delete(parent) 上的属性,但这只会发生在 childRepository.delete(child) 上。父删除抛出异常
解决方案
解决方案是大约 3 小时谷歌搜索......这个想法是设置自定义外键
@ElementCollection(fetch = FetchType.EAGER)
@CollectionTable(name = "child_properties"
,joinColumns = {
@JoinColumn(name = "child_id"
, referencedColumnName = "id"
,foreignKey=@ForeignKey(name="CHILD_PROPERTY_FK"
, foreignKeyDefinition = "FOREIGN KEY (child_id) references public.child (id) MATCH SIMPLE ON UPDATE NO ACTION ON DELETE CASCADE"))
}
)
@MapKeyColumn(name = "name")
@Column(name = "value")
private Map<String,String> properties;
推荐阅读
- javascript - 使用 api 显示列表的 Angular 8 问题
- html - Google Drive 和翻译脚本
- google-apps-script - 是否可以动态更改 gmail 插件图标?
- java - 如何使用外部映射将 json 转换为 json
- sql - TSQL - 每天返回前 10 名客户
- javascript - AngularJS 日期过滤器添加了意外的时区偏移量?
- flutter - 在颤动中更改语言后如何刷新应用程序当前屏幕?
- html - 如何在 Vue js 中将相对图像 url 转换为绝对图像 url?
- sql - SQL Server 首先按 ParentID 排序,然后是 Child
- swift - 获取 SCNNode Swift 的方向