adam bien's blog

Loading Lazy (JPA) Relations - With (J)Xpath 📎

Lazy loaded relations often cannot be transferred and serialized to the client. Even in case the serialization were successful, they cannot be accessed from the client for sure. They have to be loaded before leaving the remote-boundary. Either the server has to know in advance which references are interesting to the client, or the client has to communicate it somehow.

The latter case can be easy handled with a nice commons library with the name JXPath. The idea: a XPath expression can be applied to JavaBeans, what eventually causes the invocation of "getters" and so forces the loading of lazy relations. So a simple string can be passed from the client to the server. So to invoke the method Master#getDetail():

 public class Master {

    private Detail detail;


    private List<Detail> details;


    public Master(Detail detail) {

        this.detail = detail;

        this.details = new ArrayList<Detail>();

        this.details.add(detail);

    }


    public Detail getDetail() {

        System.out.println("getDetail");

        return detail;

    }


    public void setDetail(Detail detail) {

        this.detail = detail;

    }


    public List<Detail> getDetails() {

        return details;

    }

    public void setDetails(List<Detail> details) {

        this.details = details;

    }

...requires the following code:

public class JXPathTest {


    private Master master;


    @Before

    public void init(){

        this.master = new Master(new Detail());

    }


    @Test

    public void lazyLoadOneToOne(){

        Object value = JXPathContext.newContext(master).getValue("/detail");

        assertNotNull(value);

    }

//.. 

This sample is an interesting extension of the Service Facade pattern. Gateway solves the lazy-loading problem entirely, but requires the introduction of conversational state.

The sample project "JXPath" was pushed into:http://kenai.com/projects/javaee-patterns/ 

[See "The Problem with Lazy Loading and Transparent Persistence" pattern, page 51, "Essential Complexity Of Domain Driven Designs" , page 266, as well as the Gateway and Service Facade Patterns in "Real World Java EE Patterns Rethinking Best Practices" book for more in-depth discussion]