Lazy Loading with Flex, BlazeDS and Hibernate

DZone 's Guide to

Lazy Loading with Flex, BlazeDS and Hibernate

· Database Zone ·
Free Resource

This article takes a look at some of the problems associated with sending complex object graphs from Java to Flex, a few common workarounds and how lazy loading presents a more effective solution.

We'll take a look at one of the open source solutions available to facilitate the solutions discussed – dpHibernate - and step through setting it up.

Additionally, we'll cover off a brief overview of how it all works, and some of the common pitfalls.

The sample project discussed in this article is available to be checked out here

The problem part one:  LazyInitializationException

BlazeDS does not provide any out-of-the-box support for Lazy Loading, or support of Hibernate lazy-loaded entities.

When a server method returns an entity fetched from the database via hibernate, developers will often see a LazyInitializationException  thrown from Hibernate / BlazeDS.

This is because the hibernate session that was used to fetch from the database is closed after the call exits the DAO layer.  During serialization, BlazeDS traverses the accessors of an object, calling each and serializing it's value.  If it hits a property which Hibernate has proxied, a LazyInitializationException is thrown, as Hibernate no longer has an active session to fetch the value from the database.


dpHibernate is an open source serialization adpater for BlazeDS, which provides lazy loading and persistence for Hibernate.  It addresses the LazyInitializationException issue by managing the hibernate session in a fashion similar to Springs' OpenSessionInViewFilter.

The database session gets opened and maintained by dpHibernate, ensuring that when BlazeDS goes to serialize a response, the database session is still available, should it be needed.

This prevents the  LazyInitializationException, and would allow the full object graph to be serialized, and returned to the flex client.

Too much data

While having the ability to return the full object graph to the client is handy, it's not very realistic in a real-world scenario.  This can often result in very bloated object graphs being sent across the wire, and needlessly incurring expensive serialization & deserialization.  DpHibernate addresses this issue, by providing true support for lazy loading of entities between Flex and Java, proxying objects being sent across the wire.

For example, here's a couple of classes from a question/answer forum application:

public class User {
String name;
Set<Post> posts;
public class Post {
String title;
String body;
User author;
Set<Post> replies;

This seemingly simple domain model turns out to be extremely expensive to serialize without lazy loading.  For example, when serializing a user, their collection of posts is serialized;  Each post includes it's own set of reply posts;  each reply includes it's author, and each author includes their full set of posts; etc.

As result, a simple call to return a single user object, could result in a heavy object graph similar to the one shown below:

public User getUser(int userId) {}


A common work-around to this problem is to use the DTO pattern, creating a trimmed down version of the User class with a subset of fields, specifically for transferring between layers.

Custom methods are then written for further drilling down into fields of an object, eg:

    public UserDTO getUser(int userId) {}
public List<PostDTO> getPostsByUser(int userId) {};
public List<PostDTO> getRepliesToPost(int postId) {};

Along with these, each Domain Object / DTO pair generally needs a translator to manage mapping between the two objects.

Lazy loading

By using dpHibernate and lazy loading, none of this extra work is required.  Instead, proxies are sent initially for collections and complex objects, and fetched on-demand when requested by the client. 

For example, the the same call to load a user against a dpHibernate service returns the following:

The response is significantly more lightweight and suitable for sending across to the client, as none of the complex objects – (eg., the Posts) are actually serialized in the initial call.  Instead, dpHibernate sends proxies for all the complex properties of the User.  As the client calls the getters for the proxied properties, their values are loaded asynchronously from the server, and populated back on the user object.

As the “posts”  collection is filled with proxies, it's length is still reported correctly.  This is useful when a collection is bound to a datagrid or list, as the grids still size correctly, and render scrollbars appropriately, even though much of the data hasn't actually been loaded on the client.  In fact, because of the way that lists &  dataGrids operate within Flex, only the items which are being rendered on-screen will be loaded from the server, rather than the full collection – a feature especially useful when working with very large datasets.

Getting started with dpHibernate

Lets look at how to set up dpHibernate in a Spring/BlazeDS project.  For this example, I'll be using the latest dpHibernate (2.0-RC3), along with Spring 3.0.  (Note that dpHibernate doesn't depend on Spring, and works just as well in environments not using Spring.)


To begin with, grab the dpHibernate download from here.

Because we're working in a Spring environment, we'll need to add the following two jars to the classpath:



Configuration:  web.xml

dpHibernate needs an active database session when sending & receiving messages with BlazeDS.  To enable this, we need a custom filter to keep the session alive:


Note – this has the same effect as adding a Spring OpenSessionInViewFilter.  So, if you already have that declared in your web.xml, you can skip this step.

Spring configuration

Next up, we need to add a few custom Spring beans.  This is a simple configuration that allows for lazy loading, and batch loading (something covered off later).

    <!-- Defines the remoting adapter, which intercepts inbound & outbound messages, and routes them thruogh dpHibernate -->
<bean id="dpHibernateRemotingAdapter"
value="org.dphibernate.adapters.RemotingAdapter" />
<property name="properties">
{"dpHibernate" :
"serializerFactory" : "org.dphibernate.serialization.SpringContextSerializerFactory"
<!-- Provides a basic service for lazy loading operations through dpHibernate.
It's also exported as a remoting destination, which makes it accessible to flex clients
<bean id="dataAccessService"
<flex:remoting-destination />
<!-- The main serializer. Converts outbound POJO's to ASObjects with dpHibernate proxies for lazy loading. Required -->
<bean id="dpHibernateSerializer"
<property name="pageSize" value="10"/>
<bean id="dpHibernateDeserializer"
scope="prototype" />

<!-- Set up the dpHibernate adapter to be the default adapter for BlazeDS -->
<flex:message-broker services-config-path="/WEB-INF/flex/services-config.xml">
<flex:remoting-service default-adapter-id="dpHibernateRemotingAdapter"
default-channels="my-amf,my-secure-amf" />

Setting up the model

In order for dpHibernate to facilitate lazy loading, entity classes must implement the org.dphibernate.core.IHibernateProxy interface, both on the Java and Actionscript classes.  Additionally, Actionscript classes must either implement IManaged, or use the [Managed] metatag.

Here's a simple example:


public abstract class BaseEntity implements IHibernateProxy {

private Integer id;
// Marked as Transient so the field is not persisted to the database by Hibernate
private Boolean proxyInitialized = true;

public Integer getId()
return id;
public void setId(Integer id)
this.id = id;
public Boolean getProxyInitialized() {
return proxyInitialized;
public Object getProxyKey() {
return id;
public void setProxyInitialized(Boolean value) {
proxyInitialized = value;

In this example, I'm using a common base class – BaseEntity – which is the base class for all entities in the project, and implementing IHibernateProxy.


public class BaseEntity implements IHibernateProxy
public var id:Number;
private var hibernateProxy:IHibernateProxy=new HibernateBean();

/* Constructor */
public function BaseEntity():void

// IHibernateProxy impl..
public function get proxyKey():Object
return hibernateProxy.proxyKey;

public function set proxyKey(value:Object):void

public function get proxyInitialized():Boolean
return hibernateProxy.proxyInitialized;

public function set proxyInitialized(value:Boolean):void

Post.as (snippet)

public class Post extends BaseEntity

Declare & initialize a dpHibernate service

The final step is to add a dpHibernate service to the project.  This service extends flex's RemoteObject class, and provides dpHibernate's functionality within the client.

First we declare the remote object within a <Declarations /> tag:

<dphibernate:HibernateRemoteObject id="dataService" destination="dataService" bufferProxyLoadRequests="true" fault="faultHandler(event)"/>

Then we initialize dpHibernate with this service as it's default:

    protected function onAppComplete(event:FlexEvent):void
// Setup a default service.
// This is used by beans to perform dpHibernate operations

Note that here we set “bufferProxyLoadRequests” to true.  This instructs the service to batch up requests to load proxies from the server where possible.  For example, when scrolling around in a List or DataGrid, several requests to fetch proxies would typically be issued to the server., (and therefore, the database).  When batching is turned on, dpHibernate uses a short delay between the first time a proxy is requested, and actually sending the call to the server.  Any other proxies that are needed during that pause get batched up into the same server call, minimizing the load on the server & database.

Setup complete!

That's it.  dpHibernate is now set up & ready to go on the project.  Calls are executed through a dpHibernate remote object the same way they would be through a normal remote object (either by declaring an operation, or be executing the method directly).

However, any results that are returned from a method call will have lazy loading enabled for all the objects which implement IHibernateProxy.

Demo Project

The above examples are taken from a demo project put together for this article – a question/answer site built on the Stack Overflow creative commons dump.  (Which is not to say I think Stack Overflow belongs in Flex, it's just a nice, freely available source of lots of data!)

The demo project displays a list of recent questions, including detailed user information, tags, comments, and the ability to drill down further into individual questions and users. 

The data is all lazy loaded on demand, keeping the amount of data transferred to a minimum, without sacrificing the richness of the flex data model.

Normally this would require many different server calls (often one per drill-down entity), translators and DTO objects.  However, thanks to the ability to lazy-load the data, only a single server method was required, and the same rich entity model is used from Java domain through to Flex domain.  (ie., No more DTO's!)

Loading some data

Now that we have our project setup and configured, dpHibernate stays out of the way.  Loading data from a remote service is exactly the same as it always was.  Let's take a look at some sample code:

public var questionList:ArrayCollection;

public function loadData():void {
var token:AsyncToken = dataService.getRecentPosts();
token.addResponder(new mx.rpc.Responder(resultHandler,faultHandler));
protected function resultHandler(event:ResultEvent):void
questionList = event.result as ArrayCollection;

protected function faultHandler(event:FaultEvent):void
Alert.show("Fault when loading data: " + event.fault.faultString);

<s:List width="100%" dataProvider="{questionList}" height="100%" contentBackgroundAlpha="0"

Here we're using the standard responder pattern to issue a call to the getRecentPosts() method on the server, and handle the result, updating the questionList ArrayCollection.  The arrayCollection serves as the dataprovider for a List, which renders as follows:

As you scroll around within in the list, you should start to see data load from the server in batches, as required.  Note that for each Post that is loaded, we're actually also expanding their “tags” collection, as required.

Clicking and drilling down into either a question or a user causes changes the view to a drill-down view, and because of the databinding in use on each of the views, triggers the data to be loaded by dpHibernate.

So, through a service method which efficiently returned a list of Post objects, we've also been able to drill down into Tags, Replies, Users and Comments, without writing any additional server calls, and without requiring any DTO objects, or translator classes.

Beware the Asynchronous server calls!

One of the major differences between a lazy loading solution implemented in Flex and one in Java, is that Flex executes all it's server calls asynchronously.  The first time the getter of a proxied value is called, dpHibernate issues a call to the server to load the value.  However, until the server's result is received, the value on the client is  either null, or an empty proxy.  Flex's databinding makes all this happen fairly transparently when working in MXML, however when working in Actionscript, developers must be wary of null values.

For example – take a look at this dummy item renderer:

<s:ItemRenderer xmlns:fx="http://ns.adobe.com/mxml/2009" >
public function get post():Post
return data as Post;

private function doSomething():void
// A NPE could be thrown here while data is being loaded
var name:String = post.author.displayName;
<!-- Flex will swallow any NPEs thrown here while data is being lazy loaded -->
<s:Label text="{post.author.displayName}" />

Accessing the post.author.displayName property is safe within a databinding statement, as Flex's dataBinding mechanism swallows null pointer exceptions.  However, accessing the same property from within actionscript can cause a null pointer to be thrown.

Further reading

More advanced configuration options are available to allow finer grained control over lazy loading behaviour – customizing how and when data is proxied.  This gives the developer the ability to further optimize the trips to the server.  Check out this article for more information.

Also, dpHibernate provides support for full CRUD operations from the client, with only a little more configuration than what has already been covered in this article.  For more information on the persistence features, check out this article.  Also, the demo project we've been working on today has been further enhanced with full persistence features.  Check out the project here. 

Finally, the dpHibernate project site and mailing list are available for support.


In this article you've seen how easy it is to get dpHibernate set up and running with lazy loading.  By using lazy loading to return a rich domain model from the server, we can minimize the amount of boilerplate services and code required to pass data between the client and server.  dpHibernate is designed to quietly work behind the scenes, with minimal configuration and pollution of your entity model.  

About the Author

Marty Pitt is an independent software developer who specializes in enterprise Java / Flex applications.  He is the lead developer of dpHibernate, and the upcoming code review tool, Marmalade.


Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}