I thought I'd share the custom UserType I wrote to allow Hibernate to deal with JBoss' MarshalledValues that it stores for serialized objects in a BLOB column. Thanks to Steve for the suggestion. I have tested this, but it's my first custom UserType so beware.
Code:
import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import net.sf.hibernate.HibernateException;
import net.sf.hibernate.UserType;
import net.sf.hibernate.lob.BlobImpl;
import net.sf.hibernate.util.SerializationHelper;
import org.jboss.invocation.MarshalledValue;
/**
* Provides Hibernate access to BLOB Objects serialized by JBoss 3.x
* CMP, which JBoss wraps in a
* org.jboss.invocation.MarshalledValue wrapper.
*
*/
public class MarshalledValueUserType implements UserType {
private static final int[] SQL_TYPES = { Types.BLOB };
public MarshalledValueUserType() { }
public int[] sqlTypes() { return SQL_TYPES; }
public Class returnedClass() { return String.class; }
public boolean equals(Object x, Object y) { return x == y; }
public Object deepCopy(Object value) { return value; }
public boolean isMutable() { return false; }
public Object nullSafeGet(ResultSet rs, String[] names, Object owner) throws HibernateException, SQLException {
Object o = rs.getObject(names[0]);
if (o instanceof MarshalledValue) {
MarshalledValue mv = (MarshalledValue) o;
try {
return mv.get();
} catch (Exception e) {
throw new HibernateException("Exception unwrapping MarshalledValue", e);
}
} else {
if (o != null) {
System.out.println("Warning: I expected a MarshalledValue object, but got: "+o.getClass().getName());
}
return null;
}
}
public void nullSafeSet(PreparedStatement st, Object value, int index) throws HibernateException, SQLException {
try {
// Wrap the Object with a JBoss MarshalledValue
MarshalledValue mv = new MarshalledValue(value);
byte[] array = SerializationHelper.serialize(mv);
st.setBlob(index, new BlobImpl(array));
} catch (IOException e) {
throw new HibernateException("Exception wrapping object in MarshalledValue", e);
}
}
}