Thursday, March 5, 2015

Solving GWT - JPA/Hibernate Problem

GWT + JPA/Hibernate Problem 

GWT is an open source framework that makes writing AJAX applications easy. Actually very easy but when you want to connect your Presentation layer (Written Using GWT) with your current Model layer (Hibernate/JPA annotated), here comes the agony.

The problem happens when you want to use your models in GWT client side, because GWT actually do compile all code in Client side to JAVASCRIPT and that require providing the source code for every java classes used in Client side.

That leaves us with several options to choose from:

A-Using DTO approach:
You can solve the problem by creating DTOs to all your models and using a mapping tool like DOZER.
But that solution is really painful, because you will have to generate DTO each time you make a small change in your Model layer.

B-Using Gilead (Hibernate for GWT).

C-Using OUR solution:
1-You will need to generate your model jar with the source code included .. it can easily achieved with maven, and also you will need to add the xxx.gwt.xml file to your model root path.
xxx.gwt.xml sample
<?xml version="1.0" encoding="UTF-8"?>
<module>
  <inherits name='com.google.gwt.user.User'/>
  <source path="model">
  </source>
</module>

For example if your models path as com.mycompany.myproject.model you will put the xml in myproject folder.

2-Now after we have a good generated model jar, now we want the GWT Compiler to understand and compile the models with hibernate annotations, this can be done easily by getting hibernate annotations jar with source code (You will find it easily by searching Google ) and add this jar to your web app class path, this will be enough to make the GWT compiler do it’s work without a problem.
Now Add your model jar to your GWT project class path and add the following entry to your gwt.xml file

<inherits name='<package-location>' />
Example: <inherits name='com.mycompany.myproject.model' />


3- Now our problem is almost solved:

How to handle hibernate entities (Persistent Set, …etc) because GWT cannot serialize this objects :

You can use Dozer for this small operation as it transform the Persistent set to its original Collection object.
How to handle lazy initialization:
Using Dozer and “CustomFieldMapper “ to replace lazy Objects with null values in the mapping operation.

No comments:

Post a Comment