POJO with other POJO references

circular-reference, hibernate, java, lazy-loading

Solution

You're describing a bidirectional association, which Hibernate has specific (and generally very good) support for.

Read up on how to do it in the docs.

Rolling this by hand is going to be quite fiddly and bug-prone. I wouldn't recommend it. Use the the power of ORM tools like Hibernate, that's what they're there for.

Problem

I am working on a API to access data stored in a system. The system contains things like people, appointments and procedures associated with those appointments. My application will strictly be read-only. I am using Spring w/ RowMapper to build objects such a "`Person`", "`Appointment`" and "`Procedure`". I have a DAO for each element. (ie: `PersonDAO.getById()`, `PersonDAO.getByName()`, ..). The issue comes in that `Appointment` has a reference to a `Person` object. An it would be nice in the `Person` object to have a reference to that `Person`'s appointments, but if I begin to load these it becomes a circular reference. So, I guess my question is the right way to handle this just put the references (Ids) in the POJOs and then have the business layer(?) just make the right calls to get the information? Or is it ok to somehow pass around a reference to the DAO in the actual POJO so that I can lazily load the object objects when referenced? But then how do you handle the circular reference? When I have a `Person` and I lazily load all their appointments, those appointments will also have a Person associated with them. When I load this `Person` it could potentially have difference information from the `Person` I am loading Appointments for. `Person` (object x) lazily load -> Appointments could lazily load `Person` (object x'). Since `Person` could have changed by the time I went to lazily load their appointments. I really need the `Person` object in `Appointment` to refer back to the same `Person` object. I'm getting all caught up on this. I know I could just "make it work", but I want to try and find a good solution. I was thinking about using hibernate for this, but thought it was really just overkill. Maybe it isn't.

Original source