Using hibernate with GWT

We can not use DAO objects directly for GWT RPC even you implement the IsSerializable or Serializable interface.

When you take an object and turn it into a Hibernate object, the object is now enhanced to be persistent. That persistence does not come without some type of instrumentation of the object. In the case of Hibernate, the Javassist library actually replaces and rewrites the bytecode for these objects by persistent entities to make the Hibernate magic work. What this means for GWT RPC is that by the time the object is ready to be transferred over the wire, it actually isn’t the same object that the compiler thought was going to be transferred, so when trying to deserialize, the GWT RPC mechanism no longer knows what the type is and refuses to deserialize it.

As a result, the DTO comes in.

We create pojos for those DAOs and create bi-direction tranfer methods for DAO and DTO.

Another way is to deproxy the object from hibernate lazy loading:

one of the side effects of Hibernate lazy loading: In order to allow lazy access to any relational objects, Hibernate returns a “proxy” object that essentially wraps and mimics the object that you wanted. This way when you call a getter, instead of throwing a NullPointerException, Hibernate can retrieve the result from the database.

Great… so what now? While the proxy object will suffice whenever you need to access a public property or method, it quickly becomes apparent that introspection and reflection present a problem. Since the proxy object is not truly an instance of the class that it is wrapping, metadata (such as annotations) are not there.


@Aspect
public class HibernateProxyUtil {

@Around("@within(DeProxy) || @annotation(DeProxy)")
 public <T> T initializeAndUnproxy(ProceedingJoinPoint pjp) throws Throwable {
 T entity = (T) pjp.proceed();
 if (entity == null) {
 return null;
 }

Hibernate.initialize(entity);
 if (entity instanceof HibernateProxy) {
 entity = (T) ((HibernateProxy) entity).getHibernateLazyInitializer().getImplementation();
 }
 return entity;
 }
}

In addition we specify this class in our applicationContext xml then we can use @Deproxy for our service layer class.

<aop:aspectj-autoproxy/>

<bean id=”deProxyAspect” class=”org.finra.cdip.cobra.server.util.HibernateProxyUtil”/>

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s