Over a million developers have joined DZone.

Hessian & Hibernate With Lazy Collections

·
// description of your code here
Use this instead of the HessianServlet when you want to use hibernate lazy loaded collections with hessian. Of cource you will have to load the collections on demand from the client side when they are needed. All uninitialized collections will sent to the client as empty array lists.

import com.caucho.hessian.server.HessianServlet;

public class HibernateHessianServlet extends HessianServlet {

    public HibernateHessianServlet() {
        setSerializerFactory(new CustomSerializerFactory());
    }
}

public class CustomSerializerFactory extends SerializerFactory {

    private ListSerializer instance = new ListSerializer();

    public Serializer getSerializer(Class cl) throws HessianProtocolException {
        return (Serializer) (AbstractPersistentCollection.class
                .isAssignableFrom(cl) ? instance : super.getSerializer(cl));
    }

    private static class ListSerializer implements
            com.caucho.hessian.io.Serializer {
        private CollectionSerializer delegate = new CollectionSerializer();

        public void writeObject(Object obj, AbstractHessianOutput out)
                throws IOException {
            if (Hibernate.isInitialized(obj))
                delegate.writeObject(new ArrayList((Collection) obj), out);
            else
                delegate.writeObject(new ArrayList(), out);
        }
    }
}
Topics:

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

{{ parent.tldr }}

{{ parent.urlSource.name }}