Search code examples
javajpaglassfishlazy-loading3-tier

Java-EE: How to design data flow in a 3-tiered application environment?


I am currently working on a distributed application using the following components:

1.tier: Database-Server -> MySQL 5.5

2.tier: Application-Server -> Glassfish 3.1.2.2

3.tier: Stand-alone Fat-Client -> Java-SE (JRE 6)

I use JPA 2.0 (eclipse-link) as persistence provider and currently passing the @Entity beans between the 2nd and 3rd tier using serialization. I use static weaving in order to benefit from lazy fetching supported by JPA.

My problem is, that because of serialization between 2nd/3rd tier lazy fetching won't work! That results in heavy network traffic, since every serialization of one of my entity beans requires that all relationships to other entities/tables are fetched before sent over the network.

How can I benefit from JPA lazy fetching in such a setup? Is there a work-around without the need to introduce leightweight DTO/DAO (this would add huge complexity to my project) ?

Many thanks for your help in advance!


Solution

  • We solved this issue by using load groups and query hints in order to define the depth of the relations that should be fetched in a particular query. This requires lazy fetching and therefore weaving when using eclipse-link as JPA provider.

    Here's a short example:

    Server side query on a particular facade:

    @Override
    public List<Contact> query(LoadGroup group) {
        TypedQuery<Contact> query = em.createQuery("SELECT c FROM Contact c", Contact.class);
        if(group!=null) { query.setHint(QueryHints.LOAD_GROUP, group); }
        return query.getResultList();
    }
    

    Client side query on that particular facade:

    LoadGroup group = new LoadGroup();
    group.addAttribute("telephone");
    group.addAttribute("address.street");
    List<Contact> contacts = remoteContactFacade.query(group);
    

    In this example the Contact table has further many-to-one relations to the Address and Telephone tables. By using the dot notation you can define the depth of what should be fetched.

    Hope this helps.