Java : Serializing Hibernate collections

This page last changed on Feb 08, 2006 by Kees de Kooter

Use case: remote use of hibernate initialized POJOs.

The following code replaces hibernate collection implementations with plain java ones on serialization. On the deserializing end the hibernate collections are not needed.

public class CustomObjectOutputStream extends ObjectOutputStream {
 
    public CustomObjectOutputStream(OutputStream outputStream) throws IOException {
    super(outputStream);
    this.enableReplaceObject(true);
    }
 
    public boolean enableReplaceObject(boolean arg0)
        throws SecurityException {
    return super.enableReplaceObject(arg0);
    }
 
    /**
     * Replace (hibernate) specific collections with generic java
     * collections.
     */
    public Object replaceObject(Object original) throws IOException {
 
    Object result = null;
 
    if (original instanceof Set) {
 
        Collection collection = (Collection)original;
 
        try {
        result = new HashSet(collection);
        } catch (Exception e) {
        result = new HashSet();
        }
 
    } else if (original instanceof List) {
 
        Collection collection = (Collection)original;
 
        try {
        result = new ArrayList(collection);
        } catch (Exception e) {
        result = new ArrayList();
        }
 
    } else {
        result = original;
    }
 
    return result;
    }
}