It's not a secret anymore!
The moose likes Object Relational Mapping and the fly likes many-to-many mapping Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Databases » Object Relational Mapping
Bookmark "many-to-many mapping" Watch "many-to-many mapping" New topic

many-to-many mapping

Venkatesh Kumar
Ranch Hand

Joined: Aug 08, 2003
Posts: 68

I have a many-to-many mapping between entities course and student with many-to-many table named as student_course.Class student has a getter/setter for the collection of course(s) and vice versa.When I update student after removing a course from the collection(collection of courses) in class student,i see that the following queries are executed on student_course table:
(eg:a student had 3 courses and 1 course is removed from the collection)

delete from student_course where student_id =?
insert into student_course values(?,?)
insert into student_course values(?,?)

Why is there a deletion of all the records and then insertion of two records for the records that are remaining in the collection?Is there a way to delete only the record that was removed from the collection instead of deleting all the courses related to the student ?

Thanks for all your responses!!!
Mark Spritzler

Joined: Feb 05, 2001
Posts: 17276

Not positive, but it kind of sounds like your mapping is uni-directional, or that you need to remove objects from each Collection on both sides in order for Hiberate to know both ids to include in that first delete and therefore know the one specific record to delete.

So Hibernate in its thinking thinks it is faster to delete all the records, then go through the one side Collection and insert then back into the database.

Just a theory here.

What is your mapping for both sides of the Many to Many?

Perfect World Programming, LLC - iOS Apps
How to Ask Questions the Smart Way FAQ
Venkatesh Kumar
Ranch Hand

Joined: Aug 08, 2003
Posts: 68
Hi Mark:

Thanks for your reply.I have many-to-many on both the sides.

I agree. Here's the link:
subject: many-to-many mapping
It's not a secret anymore!