Hello,
I have used Hibernate 3.0 for some time now, however I still consider myself as a newby. Latly I found this problem, which I did solve, however I do not know if I did solve it in the correct way.
I have the following objects. Semesters has a one to many relationship with Assignments, and an Assignment has a one to many relation with Subject.
In english this comes to that in a Semester you have more then one assignment of differen subjects.
In the Semester object I use a List to hold the different Assignments. The Assignment class has the methods get/setSemester which returns/sets the semester, get/setSubject which returns/sets the Subject and get/setId which returns/sets the id of the assignment (auto generated). The Subject class has the get/setId, get/setName and get/setDescription methods.
Now each time I change the assignments, I change the whole list. That is I do something as follows:
mySemester.setAssignments(newListOfAssignments);
However those elements in the previous list of assignment still have a reference to mySemester. And thus when I do save mySemester, I find that in the database I just added the new records, and not deleted the old ones (in the Assignments Table).
What I did , and did work is the following:
[code]
// Create a reference to the list of old assignments
List<Assignment> old = semester.getAssignments();
// Setting the selected newsletter inside the resource object.
SemesterService semesterService =
ServiceFactory.getSemesterService();
semester.setAssignments(assignments);
semesterService.update(semester);
// Removing reference of the other newsletter subscriptions of this user.
AssignmentService assignmentService =
ServiceFactory.getAssignmentService();
assignmentService.remove(old);
[/code]
That is I create a reference to the old list of assignments, I then set the new list of assignments in semester and persist the object (this will just add the new rows in the Assignments table in the database). And then I remove the assignments by setting transent all the elements in the list (This will remove the assignments from the Assignments Table in the database). This works because when i come to delete the assignments, semester no longer has a reference to those assignments.
I am sure there must be a more simple way how to implement this, and any help would me more then welcome.
Thanks,
kcorp
|