[hibernate-dev] Loading data with circular dependencies

Cheryl Li cli at corp.thelevel.com
Thu Jan 31 19:46:09 EST 2008

Hi all,
I know it doesn't seem to make much sense that there are circular 
dependencies in a data model, but the requirements make it so.
I'm coming across a problem where it becomes a "chicken or the egg" kind 
of issue...

I will described a scaled-back version of our current model with the 
following example:
(Obj1: User, Obj2: Specialization)

1) There is a Many to Many relationship between Users and 
Specializations, because many users can have many specializations.
2) There is a Many to One relationship between Specializations and 
Users, because each specialization will have a "primary contact" (aka 
user). This is not nullable either.

Now how does one load the data?
1) Load Users first, but there are ConstraintViolationExceptions since 
the Specialization objects have not been loaded.
2) Load the Specializations first, but it will complain about the null 
FK since the User object hasn't been loaded yet.

Right now I am writing a workaround in java where I will load Users 
first.  If a User object breaks the constraint, I will make a clone and 
load it without the Specializations set (clearing it manually with the 
setter). But I will keep a list of the failed User objects to load for 
later.  I will load the Specializations second.  Then finally, will try 
to load the "bad apple" Users at the end, with the Specializations set 
populated.  Hibernate should simply update the Users with the 
Specializations (and thus add records into the M-to-M junction table).

Is there something cleaner I can do to get around these circular 
dependencies?  Something I can leverage in my Hibernate mapping?


More information about the hibernate-dev mailing list