This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
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"
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.