aspose file tools*
The moose likes Object Relational Mapping and the fly likes How to persist objects having circular references using Hibernate Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Databases » Object Relational Mapping
Bookmark "How to persist objects having circular references using Hibernate" Watch "How to persist objects having circular references using Hibernate" New topic
Author

How to persist objects having circular references using Hibernate

Kumar Raja
Ranch Hand

Joined: Mar 18, 2010
Posts: 519
    
    2


Hello All,

I'm trying to run an example where Many events can be held at one single location (Many to One association), which I could run successfully, if this is a unidirectional from Event to Location. But if it needs to be bidirectional, that I should be able to retrieve events for a given location, I'm failing. Please see the below code.

Event.java


Event.hbm.xml


Location.java


Location.hbm.xml


My client application


I'm using MySQL 5.1 as the backend database and have mentioned the generator as "Native"

My question,

1) In this bidirectional relationship from Event to Location, where in Event has a reference of Location and Location has the collection of events, which one should be persisted first. Either way, I'm getting exception



Regards
KumarRaja

Christian Dillinger
Ranch Hand

Joined: Jul 20, 2009
Posts: 189
If an event can take place at different locations and each location can host different events, that's a classical many-to-many, not a many-to-one/one-to-many.
Kumar Raja
Ranch Hand

Joined: Mar 18, 2010
Posts: 519
    
    2

That is true. I initially started this application as Many to One (Many events at one location), but later gave a thought of getting all events at one location. But how do I persist these objects in database. Which one should be persisted first. Or , should I be using a third table/object to store the primary keys and break down the Many to Many mapping to two Many to One mapping.
Christian Dillinger
Ranch Hand

Joined: Jul 20, 2009
Posts: 189
It depends...
You can break the many-to-many into two one-to-manys (*my* preferred way, esp. if you want to add columns to that relation) or you can map it in normal hibernate style. You can find good samples in the hibernate reference docs.
Kumar Raja
Ranch Hand

Joined: Mar 18, 2010
Posts: 519
    
    2

Thank you very much. I will check the reference.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: How to persist objects having circular references using Hibernate