Hibernate 3.0 以上也支持 Enum类型的转换,这里以Smallint为例(当然,也可以转换为其他类型,如varchar).
首先,以下是一个枚举类型
public enum ConsumerType
{
Admin,Vistor,VIP;
}
然后,再写一个模板,实现UserType类型接口,这样就可以将以后写的枚举类型都转换为Smallint存入数据库
import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import org.hibernate.HibernateException;
import org.hibernate.usertype.UserType;
public class IntEnumUserType<E extends Enum<E>> implements UserType
{
private Class<E> clazz = null;
private E[] theEnumValues;
protected IntEnumUserType(Class<E> c, E[] e)
{
this.clazz = c;
this.theEnumValues = e;
}
private static final int[] SQL_TYPES = {Types.SMALLINT};
public int[] sqlTypes()
{
return SQL_TYPES;
}
public Class<E> returnedClass()
{
return clazz;
}
public Object nullSafeGet(ResultSet resultSet, String[] names, Object owner)
throws HibernateException, SQLException
{
final int val = resultSet.getShort(names[0]);
E result = null;
if (!resultSet.wasNull())
{
try
{
for(int i=0; i < theEnumValues.length && result == null; i++)
{
if (theEnumValues[i].ordinal() == val)
{
result = theEnumValues[i];
}
}
}
catch (SecurityException e)
{
result = null;
}
catch (IllegalArgumentException e)
{
result = null;
}
}
return result;
}
public void nullSafeSet(PreparedStatement preparedStatement,
Object value, int index) throws HibernateException, SQLException
{
if (null == value)
{
preparedStatement.setNull(index, Types.SMALLINT);
}
else
{
preparedStatement.setInt(index, ((Enum)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;
return x.equals(y);
}
}
跟着,新建一个类来实现模板
/** This class is used only in the hibernate XML configuration */
public class ConsumerTypeEnum extends IntEnumUserType<ConsumerType>
{
public ConsumerTypeEnum()
{
// we must give the values of the enum to the parent.
super(ConsumerType.class,ConsumerType.values());
}
}
最后,在mapping的xml文件中,使用如下代码
<property column="USERTPYE"
not-null="true"
name="consumerType"
type="ConsumerTypeEnum" />
注意,这里是使用 ConsumerTypeEnum 而不是 ConsumerType。
3COME考试频道为您精心整理,希望对您有所帮助,更多信息在http://www.reader8.com/exam/