Java 5枚举休眠映射
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java 5枚举休眠映射相关的知识,希望对你有一定的参考价值。
This is an example of how to map a Java 5 enum when using Hibernate ORM.
import org.hibernate.HibernateException; import org.hibernate.usertype.ParameterizedType; import org.hibernate.usertype.UserType; import java.io.Serializable; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Types; import java.util.Properties; /** * This class implements the Type that will be used in the hbm file, notice that * the JavaEnumToString & StringToJavaEnum implementation isn't provided * (all they do is to convert Enum<->String in a consistent way, same goes for * StringUtils (replaceable with apache commons StringUtils). */ public class JavaEnumUserType implements UserType, ParameterizedType { private Class<? extends Enum> enumClass; private static JavaEnumToString javaEnumToString = new JavaEnumToString(); private static StringToJavaEnum stringToJavaEnum = new StringToJavaEnum(); try { enumClass = Class.forName(enumClassName).asSubclass(Enum.class); throw new HibernateException("Class " + enumClassName + " not found ", e); } } throws HibernateException { return cached; } return value; } return (Enum) value; } return x == y; } return x.hashCode(); } public boolean isMutable() { return false; } public Object nullSafeGet(ResultSet rs, String[] names, Object owner) throws HibernateException, SQLException { if (rs.wasNull() || StringUtils.isNullOrEmpty(value)) { return null; } return stringToJavaEnum.doConvert(value.trim(), enumClass); } public void nullSafeSet(PreparedStatement st, Object value, int index) throws HibernateException, SQLException { if (value == null) { } else { st.setString(index, stringValue); } } throws HibernateException { return original; } public Class returnedClass() { return enumClass; } public int[] sqlTypes() { return SQL_TYPE; } } // For example the following bean: public class DummyBean{ private DummyEnum dummyProp; public DummyEnum getDummyProp() { return dummyProp; } public void setPageDescriptor(DummyEnum _dummyProp) { this.dummyProp = _dummyProp; } } // will be mapped in this fashion: <hibernate-mapping> <class name="com.dummy.DummyBean" table="DUMMY_TABLE"> <property name="dummyProp" column="DUMMY_PROP"> <type name="com.dummy.JavaEnumUserType"> <param name="enumClass">com.dummy.DummyEnum</param> </type> </property> </hibernate-mapping>
以上是关于Java 5枚举休眠映射的主要内容,如果未能解决你的问题,请参考以下文章