Есть две сущности со связью m2o
, я никак не могу понять как аннотацией настроить каскадное удаление всех дочерних сущностей при удалении родительской. Есть подозрение что возможно я их изначально как-то неправильно создал. Как DAO использую Spring DATA JPA, то-есть пользуюсь методом deleteById(ID id)
который уже есть в CrudRepository
.
@Data
@Entity
public class Site {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Size(min = 2, max = 255)
@Column(nullable = false)
private String name;
@Size(min = 2, max = 255)
private String country;
@Size(min = 2, max = 255)
private String region;
@Size(max = 1000)
@Column(length = 1000)
private String description;
}
@Data
@Entity
public class Sector {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne(fetch = FetchType.EAGER)
private Site site;
@Column(nullable = false)
private String name;
@Column(length = 1000)
private String description;
}
Если добавить в аннотацию cascade = CascadeType.ALL
будет следующее исключение:
2019-05-27 17:16:10.683 INFO 9350 --- [nio-8080-exec-5] f.k.escalade.controllers.SiteController : DELETE site by ID : 1
Hibernate: select site0_.id as id1_2_0_, site0_.country as country2_2_0_, site0_.description as descript3_2_0_, site0_.name as name4_2_0_, site0_.region as region5_2_0_ from site site0_ where site0_.id=?
Hibernate: delete from site where id=?
2019-05-27 17:16:10.696 WARN 9350 --- [nio-8080-exec-5] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 0, SQLState: 23503
2019-05-27 17:16:10.696 ERROR 9350 --- [nio-8080-exec-5] o.h.engine.jdbc.spi.SqlExceptionHelper : ERROR: update or delete on table "site" violates foreign key constraint "fkn2x370i2i28hqnqof5ejjo4ou" on table "sector"
Detail: Key (id)=(1) is still referenced from table "sector".
2019-05-27 17:16:10.697 INFO 9350 --- [nio-8080-exec-5] o.h.e.j.b.internal.AbstractBatchImpl : HHH000010: On release of batch it still contained JDBC statements
2019-05-27 17:16:10.700 ERROR 9350 --- [nio-8080-exec-5] o.h.i.ExceptionMapperStandardImpl : HHH000346: Error during managed flush [org.hibernate.exception.ConstraintViolationException: could not execute statement]
2019-05-27 17:16:10.711 ERROR 9350 --- [nio-8080-exec-5] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [fkn2x370i2i28hqnqof5ejjo4ou]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement] with root cause
org.postgresql.util.PSQLException: ERROR: update or delete on table "site" violates foreign key constraint "fkn2x370i2i28hqnqof5ejjo4ou" on table "sector"
Detail: Key (id)=(1) is still referenced from table "sector".
Впрочем если не добавить, то будет тоже самое.