2007: A partially loaded association oddity
Published by peter March 4th, 2007 in hibernate, java, software development.When rewriting some code to increase performance in some parts of the application I came across a rather questionable feature of Hibernate (3.2.0GA).
Consider the following (simplified) model:
The ternary association between Movies and persons has a property to store the type of the association, for example:
Stanley Kubrick, obviously a person, can be associated to the movie '2001: A Space Odyssey' where the type stored in the MoviePersonRelatedObject would be DIRECTOR and Douglas Rain (the voice of HAL 9000) would be mapped as ACTOR.
One of the views one can have shows all movies related to a person AND for each movie the person(s) associated with type DIRECTOR.
I managed to solve this in one single HQL query (sorry for the markup, I don't have a HQL highlighter):
-
SELECT
-
p FROM Person p
-
LEFT JOIN fetch p.relatedMovies AS mpr
-
LEFT JOIN fetch mpr.roleA AS movie
-
LEFT JOIN fetch movie.relatedPersons AS mpr2
-
LEFT JOIN fetch mpr2.roleB AS director
-
WHERE
-
p.id=:id
-
AND mpr2.type=:type
While I was glad it worked (and dramatically increased the performance since the previous solution used A LOT of subqueries) my colleague was actually a bit (and for good reason) shocked by it.
A problem with the code above is that it breaks some essential hibernate contracts: associations are either loaded or will be loaded when needed; Hibernate itself doesn't know about partially loaded collections.
Since hibernate indicates this object to be correctly loaded you _could_ (depending on cascade configurations) unknowingly delete data by saving it again, auch!
Architecturally the best solution for this problem would probably be the introduction of a couple of value- or transferobjects which cant be used for saving again. But then again, this does solve my problem without adding additional code to the project.... future developers should just read the documentation!
............... well actually, I'll probably refactor it tomorrow to avoid gradually losing data in the future ![]()


















0 Responses to “2007: A partially loaded association oddity”
Please Wait
Leave a Reply