Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cascade remove relation without cascade remove target

I have a ManyToMany-relation between student and teacher in a Student_Teacher-table (Entityless).

Student:       Teacher(owning-side):   Student_Teacher
1= Tim         50= Mrs. Foo            1=   1   50
2= Ann         51= Mr. Bar             2=   1   51
                                       3=   2   50
                                       4=   2   51

As you see above every Student is currently related to every Teacher.

Now I like to remove Ann and I like to use the database's cascading techique to remove entries from the Student_Teacher-table but I do neither like to remove other Students, nor Teacher, nor other relationship.

This is what I have in the Student-Entity:

@ManyToMany(mappedBy="students")
public Set<Teacher> getTeachers() {
    return teachers;
}

This is what I have in the Teacher-Entity:

@ManyToMany
@JoinTable(name="Student_Teacher", joinColumns = {
    @JoinColumn(name="StudentID", referencedColumnName = "TeacherID", nullable = false)
}, inverseJoinColumns = {
    @JoinColumn(name="TeacherID", referencedColumnName = "StudentID", nullable = false)
})
public Set<Student> getStudents() {
    return students;
}

Now I like to use the database's delete cascade functionality. I repeat: The database's delete cascade functionality targeting the Student_Teacher-table only!

The problem:

org.h2.jdbc.JdbcSQLException: Referentielle Integrität verletzt: "FK_43PMYXR2NU005M2VNEB99VX0X: PUBLIC.Student_Teacher FOREIGN KEY(StudentID) REFERENCES PUBLIC.Student(StudentID) (2)"
Referential integrity constraint violation: "FK_43PMYXR2NU005M2VNEB99VX0X: PUBLIC.Student_Teacher FOREIGN KEY(StudentID) REFERENCES PUBLIC.Student(StudentID) (2)"; SQL statement:
delete from "Student" where name='Ann'
    at org.h2.message.DbException.getJdbcSQLException(DbException.java:345)
    at org.h2.message.DbException.get(DbException.java:179)
    at org.h2.message.DbException.get(DbException.java:155)
    at org.h2.constraint.ConstraintReferential.checkRow(ConstraintReferential.java:425)

What i can not use is the

@ManyToMany(cascade={CascadeType.REMOVE})

Because of the documetation tells me:

(Optional) The operations that must be cascaded to the target of the association.

The "target" is the Teacher, so this cascade would remove the Teacher (what I do not like to remove).

Question:

How to configure the entitys to remove Ann and the relation only using the database's cascade functionality?

Proof of Concept:

I tried another feature, I have noticed the possibility to configure the foreign-key nativly like this:

@ManyToMany(cascade = { CascadeType.REMOVE })
@JoinTable(name="Student_Teacher", joinColumns = {
    @JoinColumn(name="StudentID", referencedColumnName = "TeacherID", nullable = false, foreignKey=@ForeignKey(foreignKeyDefinition="FOREIGN KEY (StudentID) REFERENCES Student ON DELETE NO ACTION"))
}, inverseJoinColumns = {
    @JoinColumn(name="TeacherID", referencedColumnName = "StudentID", nullable = false, foreignKey=@ForeignKey(foreignKeyDefinition="FOREIGN KEY (TeacherID) REFERENCES Teacher ON DELETE NO ACTION"))
})
public Set<Student> getStudents() {
    return students;
}

The problem is: This works fine but to trigger the removal of the entries in Student_Teacher I have to specify @ManyToMany(cascade = { CascadeType.REMOVE }) on both sides. Hibernate do not parse the foreignKeyDefinition and only see the CascadeType.REMOVE and drops the target-entitys (and the referenced Student Tim) out of the cache, but they are still in the database!!! So I have to clear the hibernate-session immendentelly after drop to re-read the existence of the Teachers Mrs. Foo and Mr. Bar and the Student Tim.

like image 505
Grim Avatar asked Jun 15 '17 10:06

Grim


People also ask

Is it good to use on delete cascade?

Yes, the use of ON DELETE CASCADE is fine, but only when the dependent rows are really a logical extension of the row being deleted. For example, it's OK for DELETE ORDERS to delete the associated ORDER_LINES because clearly, you want to delete this order, which consists of a header and some lines.

What does onDelete cascade mean?

The onDelete('cascade') means that when the row is deleted, it will delete all it's references and attached data too.

What is the purpose on delete cascade deletes the dependent?

ON DELETE CASCADE constraint is used in MySQL to delete the rows from the child table automatically, when the rows from the parent table are deleted. For example when a student registers in an online learning platform, then all the details of the student are recorded with their unique number/id.


2 Answers

Now I like to use the database's delete cascade functionality. I repeat: The database's delete cascade functionality targeting the Student_Teacher-table only!

Simply define the cascade deletion on the database schema level, and the database would do it automatically. However, if the owning side of the association is loaded/manipulated in the same persistence context instance, then the persistence context will obviously be in an inconsistent state resulting in issues when managing the owning side, as Hibernate can't know what is done behind its back. Things get even more complicated if second-level caching is enabled.

So you can do it and take care not to load Teachers in the same session, but I don't recommend this and I write this only as an answer to this part of the question.

How to configure the entities to remove Ann and the relation only using the database's cascade functionality?

There is no such configuration on JPA/Hibernate level. Most DDL declarations in mappings are used only for automatic schema generation, and are ignored when it comes to entity instances lifecycle and association management.

What i can not use is the

@ManyToMany(cascade={CascadeType.REMOVE})

Cascading of entity lifecycle operations and association management are two different notions that are completely independent of each other. Here you considered the former while you need the latter.

The problem you're facing is that you want to break the association from the Student (inverse side marked with mappedBy) when the Teacher is the owning side. You can do it by removing the student from all teachers to which it is associated, but that could lead to loading lots of data (all associated teachers with all their students). That's why introducing a separate entity for the association table could be a good compromise, as already suggested by @Mark, and as I suggested as well in some of my previous answers on similar topics together with some other potential improvements.

like image 72
Dragan Bozanovic Avatar answered Nov 10 '22 18:11

Dragan Bozanovic


You may create a new entity TeacherStudent for the relationship, and then use CascadeType.REMOVE safely:

@Entity
public class Student {
    @OneToMany(mappedBy="student",cascade={CascadeType.REMOVE})
    public Set<TeacherStudent> teacherStudents;
}

@Entity
public class Teacher {
    @OneToMany(mappedBy="teacher",cascade={CascadeType.REMOVE})
    public Set<TeacherStudent> teacherStudents;
}

@Entity
public class TeacherStudent {
    @ManyToOne
    public Teacher teacher;

    @ManyToOne
    public Student student;
}

You'll have to take care of the composite foreign key for TeacherStudent. You may take a look at https://stackoverflow.com/a/29116687/3670143 for that.

Another relevant thread about ON DELETE CASCADE is JPA + Hibernate: How to define a constraint having ON DELETE CASCADE

like image 41
Renan Avatar answered Nov 10 '22 18:11

Renan