adam bien's blog

Lazy Loading Entities In Views Challenge--Reader's Question And Answer 📎

Question:

"…if I have a method in a service bean implementation:
 
public List<User> getAllUsers();

and User.java is an entity class with something along the lines of:

 class User {
   List<Address> addresses;  // Lazy loaded
   List<Friend> friends;     // Lazy loaded 
}

Then in a controller, you do getAllUsers() and render the jsp/jsf where you intend to loop through all users and for each user, you write out all addresses as an example.

The problem is that since the addresses are lazily loaded, there is no good way to actually loop through and output the addresses since we are in a detached mode already in the controller, unless you add a method getAllUserWithAddresses() or make it eagerly loaded. Then one would need one for friends as well. It gets ugly pretty quickly.

Answer:

  1. If everything is needed in the UI--why not to eager load the relations?
  2. With JXPath relations could be easily loaded just by passing a String
  3. Open Session In View Pattern / Anti-Pattern
  4. Use Stateful Session Beans with "Extended" Entity Manager
  5. Use Fetch Joins they are designed to prefetch lazy relations

Most of the items above rely on stateful architecture, what may cause some discussion about scalability.

[See also an in-depth discussion in the "Real World Java EE Patterns--Rethinking Best Practices" book (Second Iteration, "Green Book"), page 48 in, chapter "The Extended Mode"]

See you at Java EE Workshops at MUC Airport (March 25th-28th)!