Just had to spend some time on this and this worked for me:
public class JSONUserType implements UserType {
private static final int[] SQL_TYPES = { Types.LONGVARCHAR };
@Override
public Object assemble(Serializable cached, Object owner)
throws HibernateException {
return deepCopy(cached);
}
@Override
public Object deepCopy(Object value) throws HibernateException {
if (value == null)
return value;
try {
return new JSONObject(((JSONObject) value).toString());
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
@Override
public Serializable disassemble(Object value) throws HibernateException {
return ((JSONObject) value).toString();
}
@Override
public boolean equals(Object x, Object y) throws HibernateException {
if (x == null)
return (y != null);
return (x.equals(y));
}
@Override
public int hashCode(Object x) throws HibernateException {
return ((JSONObject) x).toString().hashCode();
}
@Override
public boolean isMutable() {
return true;
}
@Override
public Object replace(Object original, Object target, Object owner)throws HibernateException {
return deepCopy(original);
}
@Override
@SuppressWarnings("unchecked")
public Class returnedClass() {
return JSONObject.class;
}
@Override
public int[] sqlTypes() {
return SQL_TYPES;
}
@Override
public Object nullSafeGet(ResultSet rs, String[] names,SessionImplementor session, Object owner)throws HibernateException, SQLException {
String jsonString = rs.getString(names[0]);
if (jsonString == null)
return null;
try {
return new JSONObject(jsonString);
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
@Override
public void nullSafeSet(PreparedStatement st, Object value, int index,SessionImplementor session) throws HibernateException, SQLException {
if (value == null) {
st.setNull(index, Types.OTHER);
} else {
st.setObject(index, ((JSONObject) value).toString(),Types.OTHER);
}
}
}