javahibernatemodelfetching-strategy

Hibernate modeling and fetching strategies: what to do with sparse little pieces of information


Environment:

Description:

Ok, let's say I have a web application with two domain objects:

a User can have a lot of Reports (one to many relation). Please consider that a Report is a very complex object, with a lot of attributes.

User class:

public class User { 
    private Set<Report> reports = new HashSet<Report>();
}

Report class:

public class Report {   
    //...so maaaaaaany attributes
    private String name;
}

Let's say I need to show an html page displaying a User profile with the list of associated Reports. Only reports' names appear in the list. Please comment these considerations:

  1. I don't think to eagerly load the Reports because of memory saving issues, so I'll go lazy.
  2. Even if I go lazy, the point is that I actually need the reports'name only. I don't want to load tons of information just to cherry-pick the report name!

So a possible solution is to modify the User class as follows:

public class User { 
    private Set<Report> reports = new HashSet<Report>();
    private List<String> reportNames;
}

taking the needed information from the report to the user. In my opinion, it brings two consequences:

  1. the list of report names must be kept updated
  2. i break the separation between objects domain, filling the User with information I can't easily retrieve. This approach might even be effective, but it is very ugly.

So is there a nice solution to cope with this problem? I think it is common issue for developers.


Solution

  • One way would be to use the following pattern:

    The DAO method could make sure to only read the required data, or you could do that transformation in the service layer. It is really a bit of what you prefer, and how it fits in. But do not make the DAO layer aware of your UserViewObject.