使用@OneToMany删除子级

时间:2018-11-30 12:00:39

标签: java hibernate spring-boot

我有一些课程:

enter image description here

图片:

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;

AdditionalInfo:

public class AdditionalPictureInfo {

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

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

URLScanResult:

public class URLScanResult {

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

@ManyToOne
@JoinColumn(name = "scan_id")
private URLScan 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关联的问题。评论和其他信息将被删除。有人可以解释为什么会发生这种情况以及如何解决吗?

我正在使用Spring Boot并进入休眠状态。

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

感谢评论。为了澄清:

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一起使用?

0 个答案:

没有答案