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);
                delegate.writeObject(new ArrayList(), out);

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}