首页 > 解决方案 > 使用 @OneToMany 删除子级

问题描述

我有一些课程:

在此处输入图像描述

图片:

public class Picture {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@OneToMany(cascade = CascadeType.ALL, mappedBy = "picture", fetch = FetchType.LAZY, orphanRemoval = true)
private Set<AdditionalPictureInfo> additionalInfo = new HashSet<>();

@OneToMany(cascade = CascadeType.ALL, mappedBy = "picture", fetch = FetchType.LAZY, orphanRemoval = true)
private Set<Comment> comments = new HashSet<>();

@OneToMany(cascade = CascadeType.ALL, mappedBy = "picture", fetch = FetchType.LAZY, orphanRemoval = true)
private Set<URLScanResult> urlScanResults = new HashSet<>();

评论:

public class Comment {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@ManyToOne
@JoinColumn(name = "picture_id")
private Picture picture;

附加信息:

public class AdditionalPictureInfo {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@ManyToOne
@JoinColumn(name = "picture_id")
private Picture picture;

网址扫描结果:

public class URLScanResult {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@ManyToOne
@JoinColumn(name = "scan_id")
private URLScan urlScan;

网址扫描:

public class URLScan {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;


@OneToMany(cascade = CascadeType.ALL, mappedBy = "urlScan", fetch = FetchType.EAGER, orphanRemoval = true)
private Set<URLScanResult> results = new HashSet<>();

在我的用例中,我想删除图片以及相关的评论、附加信息和 url 扫描结果。一切都适用于评论和附加信息。如果图片是从 URLScanResults 中引用的,则会出现以下异常:

Caused by: org.h2.jdbc.JdbcSQLException: Referential integrity constraint violation: "FK1AA1C1T58EMNCAAG78CVTYMFH: PUBLIC.URL_SCAN_RESULT FOREIGN KEY(PICTURE_ID) REFERENCES PUBLIC.PICTURE(ID) (3)"; SQL statement:

我理解这个例外,但我不知道为什么在删除图片之前,关联的 URLScanResult 实体没有被删除。我想这是 URLScanResult 也与 URLScan 相关联的问题。评论和附加信息被删除。有人可以解释为什么会发生这种情况以及如何解决吗?

我正在使用弹簧启动和休眠。

///////////////////////////////////////// /////////////////

感谢您的评论。澄清一下:

Hibernate: delete from additional_picture_info where id=?
Hibernate: delete from comment where id=?
Hibernate: delete from picture where id=?
2018-11-30 20:21:56.062  WARN 14251 --- [io-10080-exec-8] o.h.engine.jdbc.spi.SqlExceptionHelper   : SQL Error: 0, SQLState: 23503
2018-11-30 20:21:56.062 ERROR 14251 --- [io-10080-exec-8] o.h.engine.jdbc.spi.SqlExceptionHelper   : ERROR: update or delete on table "picture" violates foreign key constraint "fk1aa1c1t58emncaag78cvtymfh" on table "url_scan_result"
Detail: Key (id)=(1) is still referenced from table "url_scan_result".

查找 sql 日志。在删除图片之前删除评论和附加信息。我知道我可以先手动删除每个 URLScanResult 但为什么它会自动与 Comments 和 Additional Info 一起使用?

标签: javahibernatespring-boot

解决方案


推荐阅读