Hi experts,
I have a one-to-many relationship for a user and his books where a user can have many books. I used list to achieve this relationship. The problem is when I want to replace existing list with a totally new list and save it back, the previous book items will not be deleted except for their foreign keys being removed. I am not sure whether this is desired behaviour of one-to-many relationship. I even have tried cascade="all-delete-orphan" in the list declaration. The following code snippets will show you what I was trying to do
Code:
User user = userManager.getUser("01"); //Retrive the user and its associated books
List list = new ArrayList();
Book book = new Book(new Integer(1),"Book 1");
list.add(book);
user.setBooks(list);// Replace previous list of book with new book list
userManager.saveUser(user); //When we save here, hibernate should delete all previous books and insert new books. The new book lists are inserted but the old lists are not deleted but only their foreign key reference to the user is cleared.
Here is corresponding hibernate mapping:
Code:
<class name="User" table="User">
<id column="UserId" name="userId">
<generator class="native"/>
</id>
.........
<list name="books" cascade="all-delete-orphan">
<key column="userId"/>
<index column="idx"/>
<one-to-many class="Book"/>
</list>
</class>
<class name="Book" table="Book">
<id name="id" >
<generator class="native"/>
</id>
........
</class>