File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Object Relational Mapping and the fly likes Hibernate - Duplicate child mysteriously added Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Databases » Object Relational Mapping
Bookmark "Hibernate - Duplicate child mysteriously added" Watch "Hibernate - Duplicate child mysteriously added" New topic

Hibernate - Duplicate child mysteriously added

Blake Minghelli
Ranch Hand

Joined: Sep 13, 2002
Posts: 331
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?

Blake Minghelli<br />SCWCD<br /> <br />"I'd put a quote here but I'm a non-conformist"
Mark Spritzler

Joined: Feb 05, 2001
Posts: 17276

Maybe the parent just had twins.
Just kidding of course.

Perfect World Programming, LLC - iOS Apps
How to Ask Questions the Smart Way FAQ
Blake Minghelli
Ranch Hand

Joined: Sep 13, 2002
Posts: 331
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.
I agree. Here's the link:
subject: Hibernate - Duplicate child mysteriously added
It's not a secret anymore!