Chop Hibernate Lazy Associations


<!–[if gte mso 9]>

Normal</w:view> 0</w:zoom> false</w:saveifxmlinvalid> false</w:ignoremixedcontent> false</w:alwaysshowplaceholdertext> EN-US</w:lidthemeother> JA</w:lidthemeasian> X-NONE</w:lidthemecomplexscript> </w:usefelayout></w:overridetablestylehps></w:dontflipmirrorindents></w:enableopentypekerning></w:splitpgbreakandparamark></w:dontgrowautofit></w:useasianbreakrules></w:wraptextwithpunct></w:snaptogridincell></w:breakwrappedtables></w:compatibility> </m:narylim></m:intlim></m:wrapindent></m:defjc></m:rmargin></m:lmargin></m:dispdef></m:smallfrac></m:brkbinsub></m:brkbin></m:mathfont></m:mathpr></w:donotpromoteqf></w:validateagainstschemas></w:punctuationkerning></w:trackformatting></w:trackmoves></w:worddocument> </xml><![endif]-->

In many Java application architectures, the domain model is been used by the presentation tier as the “Model” in MVC architecture. This can be done with various Java Web Framework: Spring-MVC, JSF, GWT etc.

However, in many cases this is not the case, and you have different client-server architecture. The presentation tier might reside in a different process, for example: JavaScript, Flex, Silverlight and have their own process (or at least “live” within the browser process). In this case the client has its “own” model, which resides in a different address space at runtime than the server. The server may use one or more serialization libraries to marshal/unmashal its domain model to the client. For example, if you use REST as your client-server architecture, you may use Jackson. If you use SOAP as your communication protocol, you may use JAXB. If you have FLEX client, you may use BlazeDS. Sometimes, you may even use a few serialization mechanisms in the same application, since you may have more than client type.


And here comes the problem…


If you reuse your Hibernate entities as an output of your api to the client, you will probably probably face “org.hibernate.LazyInitializationException”.

The reason for this, is the way Hibernate load entities from the DB: Whenever you use a persistent Collection or MAP in your domain model, Hibernate will use its own implementation, and by default will NOT load this map or collection, unless you explicitly load it, or request it in your query. More than that – “ManyToOne” and “OneToOne” association can also be declared as lazy. In this case Hiberante will use a Proxy, which will act as a “lazy” mediator, and will load the lazy association only upon request.

In general, this Hibernate “laziness” approach is great – You can load lazy associations on the server while your code is in the transaction boundaries. As long as your presentation layer is in the same address space as the server, it doesn’t make any problem to the client - The presentation layer will render only the loaded entities graph, which was fetched by Hibernate at the server tier.


But what should we do in the second architecture type? What should we do when the client tier is on a different address space than our Java server – i.e. Silverlight, JavaScript, Flex or any external application? How can the serialization frameworks translate the results from the server to the client, when the output from the server contains lazy Hibernate associations?


There are several approaches to this. One of them is simply decouple the domain model completely from the clients by using yet another layer – DTO (Data Transfer Objects). This decouple is an advantage, since there is a separation between the client and server code. However, personally, I don’t like them much, since they put a parallel hierarchy to the domain model. A change in one place usually makes a change in the second hierarchy, and there is a lot of code to translate from and back the domain model to the DTOs. Even with libraries like Dozer, you will still have to maintain a parallel hierarchy.

Many times it’s easier to use the same model all over. So I looked for a solution that “chop” all lazy associations, just before marshaling the entities to the client. Since I haven’t found any library that does it, I decided to develop such a “chopping library”, and this is what we did in one of our customers.

We called it “Hibernate Lazy Chopper” – and the idea is simple: Whenever the results comes out of the server to the client, just before the serialization framework apply its marshaling, the framework goes over all the object graph recursively, and “chop” lazy associations. This chopping works on both Hibernate lazy collections and Hibernate lazy proxies, and uses Spring AOP mechanism.


Here are the technical details, for how you should use the lazy chopper:

1.  Add Tikal Maven Repository with the following URL :



2.  Add it as a Maven dependency to your project:


3.  Add lazy chopper beans to your application by including its application context file:

<import resource="classpath:lazychopper-ApplicationContext.xml"/>


4.     Declare 2 properties on your application properties file (I assume you already included this file with PropertyPlaceHolderConfigurer)

a.     modelpackage -  This is the package to scan lazy entities on your domain model. For example:

b.     abstractEntityClass – Your base class for your entities, that each entity  that is scanned for lazy associations should be inherited from. For example:

5.  Declare a pointcut named “allServices” in your application context that represent your service layer. This Pointcut will be use to apply the lazy chopping – When a service in this layer finishes, the lazy chopper will apply the chopping the output graph. Here is an example

  <aop:pointcut id="allServices" expression="execution(**Service.*(..))" />

6.  Configure your transaction advice to be higher order number than 10 (the choppingAdvice’s order value) – This makes sure, the chopping advice should take place **after** the transaction advice. Otherwise the chopped entities would have been be modified in the DB, since they would have been in the transaction context. So change the aop:config above and add the transaction advice as follow:

  <aop:pointcut id="allServices" expression="execution(**Service.*(..))" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="allServices" order="200" />


That’s it!


Now whenever, a client will call your server, you will NOT get the LazyIntinalizationException. You can use this library from against any client or external system to your server, and it does NOT matter which protocol or serialization mechanism is been used.


The sources for the project can be downloaded from GitHub here.


















Big-Data and Backend-Architect

Backend Group

Thank you for your interest!

We will contact you as soon as possible.

Want to Know More?

Oops, something went wrong
Please try again or contact us by email at
Thank you for your interest!

We will contact you as soon as possible.

Let's talk

Oops, something went wrong
Please try again or contact us by email at