This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
i'm just starting to work with hibernate and i have this situation i don't really understand. maybe someone can explain?
i have a product object that has a parent which is again a product. hibernate mapping looks something like this:
then in my code i load a product, set a new parent and try to save:
but i get an exception: JDBCExceptionReporter - Duplicate key or integrity constraint violation message from server: "Cannot add or update a child row: a foreign key constraint fails"
if i save the parent before i save the product, it works. however, i was expecting the cascade settings to take care of this somehow. why is this not the case? and how can i use these cascades correctly then?
many thanks, jan
[ January 05, 2005: Message edited by: Jan Vandernoot ] [ January 05, 2005: Message edited by: Jan Vandernoot ]
I'm fairly new to Hibernate myself, and with my object graphs I always save the root element, but here are a couple things you might want to try out.
Don't you need to call parent.getChildren().add(product), too?
In my parent-child relationships, the inverse attribute in the <set> tag is set to "true". Maybe this will help?
If you do #1, then you can save the parent instead of the product.
[ January 05, 2005: Message edited by: David Harkness ]
Joined: Mar 05, 2002
Alright, I got it working... Mentioning the inverse attribute made me look that up in the manual again and there it was:
Changes made only to the inverse end of the association are not persisted (...) The non-inverse side is used to save the in-memory representation to the database.
So it the cascade was actually working just fine, the problen was with the bidirectional association! I actually had the inverse attribute set correctly (see my mapping above), but I was trying to save on the inverse side and it needs to be the other way around.
For completeness, here's the working code (the difference is in the last line!):
Joined: Jul 08, 2004
Thanks for posting the code. Here is reference to a site which in detail describes what happens when inverse attribute is used. All the generated queris are even posted. Nice.