Hibernate version : 4.1
Annotation configuration
Hi,
I have two entities:
Code:
public class Teacher {
@OneToMany(fetch=FetchType.LAZY, mappedBy="teacher", cascade=CascadeType.ALL, orphanRemoval=true)
public Set<Student> getStudents(){....}
}
public class Student {
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="teacher_id", nullable=false, updatable=false, insertable=false)
public Teacher getTeacher() {...}
}
All the merge operations on Teacher work perfectly fine with cascade operations including deletion of students in a single session. However, the problem arises with use of multiple sessions as in the case of a web application. Here is the scenario
Code:
Hibernate Session 1:
Step 1: Get Teacher by id and initialize child students using session.initializeCollection(teacher.getStudents());
Step 2: Add new student (name=xx) using teacher.getStudents().add(student);
Step 3: Merge Teacher to cascade insert of new student (xx). This results in an insert query for the newly added student
Hibernate Session 2: (Another web user)
Step 1: Get same Teacher as in Session 1 by id and initialize child students using session.initializeCollection(teacher.getStudents());
Step 2: Before Step 3 in Session 1, add a new student (name=yy) using teacher.getStudents().add(student);
Step 3: Merge Teacher to cascade insert of new student (yy). This results in an insert query for the newly added student but also results in a delete for the student(xx) added in session 1
Step 3 of session 2 is the main problem. How can I achieve concurrency for the student collection? I tried using @version on Teacher and student but the Teacher's version is not updated when the only changes to the Teacher entity are the modification of student collection.
Can someone suggest on how to solve this problem or if there any other pattern to achieve this?
Thanks
Note: I am using Hibernate with Spring Transaction Management and OpenSessionInViewFilter. Not sure if that has anything to do with this problem.