tags:

views:

1015

answers:

3

The situation is this:

  • You have a Hibernate context with an object graph that has some lazy loading defined.
  • You want to use the Hibernate objects in your UI as is without having to copy the data somewhere.
  • There are different UI contexts that require different amounts of data.
  • The data is too big to just eager load the whole graph each time.

What is the best means to load all the appropriate objects in the object graph in a configurable way so that they can be accessed without having to go back to the database to load more data?

+2  A: 

Let's say you have the Client and at one point you have to something with his Orders and maybe he has a Bonus for his Orders.

Then I would define a Repository with a fluent interface that will allow me to say something like :

new ClientRepo().LoadClientBy(id)
                .WithOrders()
                .WithBonus()
                .OrderByName();

And there you have the client with everything you need. It's preferably that you know in advance what you will need for the current operation. This way you can avoid unwanted trips to the database.(new devs in your team will usually do this - call a property and not be aware of the fact that it's actually a call to the DB)

sirrocco
+1  A: 

If it's a webapp and you're using Spring, then OpenSessionInViewFilter could be the solution to your problems.

Don
That doesn't solves the problem "without having to go back to the database", because that's exactly what the open session will do...
jrudolph
And the whole use case for this is using it with GWT which menas that there is no database connection available without having to do some clever AJAX back to the server to do the database query.
Peter Kelley
A: 

An approach we use in our projects is to create a service for each view you have. Then the view fetches the sub-graph you need for this specific view, always trying to reduce the number of sqls send to the database. Therefore we are using a lot of joins to get the n:1 associated objects.

If you are using a 2-tier desktop app directly connected to the DB you can just leave the objects attached and load additional data anytime automatically. Otherwise you have to reattach it to the session and initialize the association you need with Hibernate.initialize(Object entity, String propertyName)

(Out of memory, maybe not 100% correct)

Roland Schneider