Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Many to Many Mapping: Link table not getting updated

 
Stanley Walker
Ranch Hand
Posts: 87
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 189
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


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
Posts: 87
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yes...it helps...
thank you deepali
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic