I am in the process of migrating an application from Hibernate 4.3 to Hibernate 6.2. I have noticed something that works differently, causing duplicate records to be created in the database when there is many-to-many relation implemented with a middle entity containing additional fields and two many-to-one relations enabling full cascading. Here is our example (simplified). Imagine having students and courses and a table/entity mapping enrollments of students to courses containing additional fields like timestamp, grade, etc. Student entity:
Course entity:
Enrollment entity (many-to-many relation between courses and students):
Now, imagine that a student and two courses already exist, and we want to enroll the student into the two courses like this:
This, however, creates four records, two for each relation. The following code returns four lines
Returns the following output
Id,Student,Course,Score 7ce95b57-8664-4261-871e-60d5beaf1069, John,BIOL 101,20 2189a22a-3d03-40db-9627-adc57118cbae, John,ENGL 101,10 866c83a3-1dfd-42b1-8d1f-7d8b58168314, John,ENGL 101,10 2d91cc26-3863-4e47-9439-64512a89ad2b, John,BIOL 101,20
The problem does not occur when
- the student is being created together with the new enrollment records (i.e. when calling hibSession1.persist(s1))
- when each enrollment is persisted before merging the student
- when one of the relations (e.g., Course.enrollments) does not cascade
Is that intentional? We have several such relations in our application, and we never had this issue in the past using Hibernate 3 or 4. See the attached files for the whole test. |