views:

746

answers:

6

When calling a remote service (e.g. over RMI) to load a list of entities from a database using Hibernate, how do you manage it to initialize all the fields and references the client needs?

Example: The client calls a remote method to load all customers. With each customer the client wants the reference to the customer's list of bought articles to be initialized.

I can imagine the following solutions:

  1. Write a remote method for each special query, which initializes the required fields (e.g. Hibernate.initialize()) and returns the domain objects to the client.

  2. Like 1. but create DTOs

  3. Split the query up into multiple queries, e.g. one for the customers, a second for the customers' articles, and let the client manage the results

  4. The remote method takes a DetachedCriteria, which is created by the client and executed by the server

  5. Develop a custom "Preload-Pattern", i.e. a way for the client to specify explicitly which properties to preload.

+1  A: 

I have used 1 in the past and it worked well.

Paul Whelan
A: 

I know this is not an answer, but this makes an interesting read: http://opensource.atlassian.com/projects/hibernate/browse/EJB-255

Sietse
+1  A: 

I think number 5 is why there is a "fetch" clause in HQL. Could you use that or is the problem more complex?

Sietse
this type of eager fetching is limited for some kinds of queries
cretzel
A: 
Yuval
+1  A: 

I've been at a customer who standardised its' projects on #5 and it worked really well. The final argument of a service call was a comma-separated list of all properties to be loaded, for example:

CustomerService.getCustomerById(id, "parent, address, address.city")

I believe they used the fetch clause for this. I implemented the same idea once for jpa using PropertyUtils to trigger the lazy loading.

Glever
A: 

If your remote service only exists to provide your client with data, then switching off lazy loading on all the Hibernate entities might help.

Personally, however, I think DTOs are the right way to go. By expressing your remote interface in terms of DTOs you are sure that you get everything you need, and nothing you did not expect.

Vihung