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 Code:
1. <?xml version="1.0" encoding="UTF-8"?>
2. <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN"
3. "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
4. <hibernate-mapping>
5. <class name="entityobject.Category" table="category" schema="dev_mds">
6. <id name="categoryId" column="cat_id" type="string">
7. <generator class="sequence">
8. <param name="sequence">seq_id</param>
9. </generator>
10. </id>
11. <property name="categoryName" type="string" column="cat_name" />
12. <set name="bookset" table="cat_book_xref" schema="dev_mds" cascade="save-update">
13. <key column="cat_id"/>
14. <many-to-many class="entityobject.Book" column="book_id"/>
15. </set>
16. </class>
17. </hibernate-mapping>
Book.hbm.xml Code:
# <?xml version="1.0" encoding="UTF-8"?>
# <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN"
# "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
# <hibernate-mapping>
# <class name="entityobject.Book" schema="dev_mds" table="book">
# <id name="bookId" column="book_id" type="string">
# <generator class="sequence">
# <param name="sequence">SEQ_ID</param>
# </generator>
# </id>
# <property name="bookName" column="book_name" type="string" />
# <set name="categorySet" table="cat_book_xref" inverse="true" schema="dev_mds">
# <key column="book_id"/>
# <many-to-many class="entityobject.Category" column="cat_id" ></many-to-many>
# </set>
# </class>
# </hibernate-mapping>
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:
Code:
# session=..code for getting session...
# Category category= session.load(Category.class,"25");
# Book book= new Book();
# book.setName("Archer");
# Set<Book> bookset= new HashSet<Book>();
# bookset.add(book);
# category.setBookSet(bookset);
# session.save(category);
# //....code for commiting transaction and closing session
Please help with this. I would be grateful.