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

Hibernate - Duplicate child mysteriously added

 
Blake Minghelli
Ranch Hand
Posts: 331
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorry this is long... I'm working on my first Hibernate project and I cam across an unusual problem. I have a Customer class (abbreviated): And a Check class (abbreviated): So, as you can see, there is a one-to-many relationship between Customer and Check. My Customer.hmb.xml file specifies it's relationship like this: And my Check.hbm.xml file has this:
Here's what's wrong. Let's say my Customer object is loaded from the db with 5 checks (checks List not initialized yet though). I add a Check (Customer.addCheck) and commit the tx. When Hibernate calls getCheckCount() so it can be saved, the printList() method shows that there are 7 checks - the check I entered is duplicated in the List (but a duplicate is not inserted in the table).
I know what you're thinking: "must be a logic error, e.g. your client is calling addCheck() twice". Nope.
If I run that same exact code and just uncomment the printList() call from within the addCheck() method, (thereby forcing the collection to be loaded from the database after the check is added) then when Hibernate calls getCheckCount(), it correctly returns 6 and the printList method shows the 6 checks correctly.
What am I doing wrong?
 
Mark Spritzler
ranger
Sheriff
Posts: 17278
6
IntelliJ IDE Mac Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Maybe the parent just had twins.
Just kidding of course.
Mark
 
Blake Minghelli
Ranch Hand
Posts: 331
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I found the answer (kind of). According to the Hibernate FAQ regarding "weird problems":
Also, make sure that a call to an accessor method couldn't do anything wierd ... like initialize a lazy collection or proxy
So my options are to:
A) Don't lazily initialize the checks List
B) Increment/Decrement an internal check counter every time a Check is added/removed from the list.
I guess this is an example of the trade-offs of using Hibernate. It is not completely transparent since there are some rules that your objects have to abide by. Of course Hibernate readily admits that and they do warn the users.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic