aspose file tools*
The moose likes Object Relational Mapping and the fly likes Many to Many Mapping: Link table not getting updated 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: Link table not getting updated" Watch "Many to Many Mapping: Link table not getting updated" New topic
Author

Many to Many Mapping: Link table not getting updated

Stanley Walker
Ranch Hand

Joined: Sep 23, 2009
Posts: 87
I am trying to learn hibernate and faced this issue en route.
I am trying out a many to many mapping. To do so i have created a Category and a Book table. The link table that i have created in cat_books_xref table which simply contains the primary keys of both the tables.

My Mapping are as below:

Category.hbm.xml



Book.hbm.xml




When i add a new category and a new book everything goes fine. However when i want to add a new book to an existing category the following happens:

1. Category table is not updated, no rows are added. This is expected.
2. New row is added in Book table. Again this is excpected.
3. There should a new row in the link table with the old category id and the newly generated book id. However this is not happening. Instead the existing row is updated with the new bookid.

Have i done something wrong in the mapping.
The code i am using to add a new book to existing category is like below:



Please help with this. I would be grateful.
Deeps Mistry
Ranch Hand

Joined: Jan 31, 2009
Posts: 189


Line no 6 : you are deleting the previous reference of the book set and adding a new one. Hence when you say update, hibernate will first delete the existing record in the table and add a new one.

Instead, you have to get the reference of the book set and add a new book to the same reference.

Try this :
Category category= session.load(Category.class,"25");
category.getBookSet.add(new Book());

session.save(category);

Hope this helps.
Stanley Walker
Ranch Hand

Joined: Sep 23, 2009
Posts: 87
yes...it helps...
thank you deepali
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Many to Many Mapping: Link table not getting updated
 
Similar Threads
insert expression as primary key, taking advantage of generator class mappings?
one-to-many relation
Foreign Key Constraint Fails
hibernate class A containing a list of B
Cascading non foreign key to Child Table