Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to persist objects having circular references using Hibernate

 
Kumar Raja
Ranch Hand
Posts: 547
2
Hibernate Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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


 
Christian Dillinger
Ranch Hand
Posts: 197
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 547
2
Hibernate Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 197
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 547
2
Hibernate Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you very much. I will check the reference.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic