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:

Movies and persons 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):

SQL:
  1. SELECT
  2.   p FROM Person p
  3.   LEFT JOIN fetch p.relatedMovies AS mpr
  4.   LEFT JOIN fetch mpr.roleA AS movie
  5.   LEFT JOIN fetch movie.relatedPersons AS mpr2
  6.   LEFT JOIN fetch mpr2.roleB AS director
  7. WHERE
  8.   p.id=:id
  9.   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”

  1. No Comments

Leave a Reply





About

Welcome to the weblog of Peter Maas. Here you'll find various posts related to stuff I like (like my kids and espresso) and stuff I do (like developing software).

JavaOne 2008 Pictures

raadhuis_trap IMG_4571 robin_met_zijn_hyundai_horloge_foon nog één stapje naar achteren Sjoerd met speer konijn IMG_4707.JPG sjoerd op klimrek Charles Nutter on JRuby IMG_4602 brug IMG_4599 maan golden_gate_warning_sign nemo pub IMG_6130 heart
View more photos >

Categories



Meld u aan voor PayPal en begin direct met het accepteren van creditcardbetalingen.