Hibernate 实现Enum转换为Smallint

2008-08-25 15:48:30 来源:中国自学编程网 作者:佚名 点击:
Hibernate 3.0 以上也支持 Enum类型的转换,这里以Smallint为例(当然,也可以转换为其他类型,如varchar).



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="c
9 7 3 1 2 4 8 :



本类最新行业评测技巧教程学院
本类热点本日本周本月
本类推荐本日本周本月

广告联系 | 版权说明 | 意见建议 | 加入收藏 | 军网站群 [ 军软件园 - 军软件商城 - 军软件园论坛 ]

电信与信息服务业务经营许可证:京ICP证050203