JPA Hibernate - cascade delete in both database and annotation JPA Hibernate - cascade delete in both database and annotation database database

JPA Hibernate - cascade delete in both database and annotation


if you declare cascade in the database and hibernate the database will always delete first if it supports it and the hibernate calls will not really delete anything but run anyway. However, since you are using hibernate its main advantage is to allow easy transition to a new database which may not support database side cascade ability. Thus you would want to leave them in there even if your database supports cascade and the hiberate underlining jdbc statements are not currently doing anything (they may do something in the future)


Why would you even consider it? It is best to stick with hibernate cascade options. On the other side having cascade on both sides would run cascade delete two times. Once from hibernate and once managed by database.

Example 189. from hibernate 5.2 docs. which generates below sql.

@Entity(name = "Person")public static class Person {    @ManyToMany(cascade = {CascadeType.DELETE})    private List<Address> addresses = new ArrayList<>();    ...}Person person1 = entityManager.find( Person.class, personId );entityManager.remove( person1 );
DELETE FROM Person_AddressWHERE  Person_id = 1DELETE FROM PersonWHERE  id = 1

Now you see that hibernate deletes child entities before it deletes parent. Database cascade will run on sql person delete but it has nothing to remove now when children were removed before.