*/
public Object assemble(Serializable cached, Object owner){
return cached;
}
/*
* Transform the object into its cacheable representation. At the very least this
* method should perform a deep copy if the type is mutable. That may not be enough
* for some implementations, however; for example, associations must be cached as
* identifier values. (optional operation)
*/
public Serializable disassemble(Object value) {
return (Serializable)value;
}
/*
* During merge, replace the existing (target) value in the entity we are merging to
* with a new (original) value from the detached entity we are merging. For immutable
* objects, or null values, it is safe to simply return the first parameter. For
* mutable objects, it is safe to return a copy of the first parameter. For objects
* with component values, it might make sense to recursively replace component values.
*/
public Object replace(Object original, Object target, Object owner){
return original;
}
}
然后再hbm.xml中定义映射关系:
[html] view plaincopyprint
延伸:
为每个枚举类型定义一个UserType是比较麻烦的,可以定义一个抽象类。
例如扩展下例即可适用于所有保存为index的枚举类型
[java] view plaincopyprint
public abstract class OrdinalEnumUserType
protected Class
protected OrdinalBasedEnumUserType(Class
this.clazz = clazz;
}
private static final int[] SQL_TYPES = {Types.NUMERIC};
public int[] sqlTypes() {
return SQL_TYPES;
}
public Class< > returnedClass() {
return clazz;
}
public E nullSafeGet(ResultSet resultSet, String[] names, Object owner)
throws HibernateException, SQLException {
//Hibernate.STRING.nullSafeGet(rs, names[0])
int index = resultSet.getInt(names[0]);
E result = null;
if (!resultSet.wasNull()) {
result = clazz.getEnumConstants()[index];
}
return result;
}
public void nullSafeSet(PreparedStatement preparedStatement,
Object value,int index) throws HibernateException, SQLException {
if (null == value) {
preparedStatement.setNull(index, Types.NUMERIC);
} else {
//Hibernate.String.nullSafeSet(st, sex, index);
preparedStatement.setInt(index, ((E)value).ordinal());
}
}
public Object deepCopy(Object value) throws HibernateException{
return value;
}
public boolean isMutable() {
return false;
}
public Object assemble(Serializable cached, Object owner)
throws HibernateException {
return cached;
}
public Serializable disassemble(Object value) throws HibernateException {
return (Serializable)value;
}
public Object replace(Object original, Object target, Object owner)
throws HibernateException {
return original;
}
public int hashCode(Object x) throws HibernateException {
return x.hashCode();
}
public boolean equals(Object x, Object y) throws HibernateException {
if (x == y)
return true;
if (null == x || null == y)
return false;