/ Published in: Java
This is an example of how to map a Java 5 enum when using Hibernate ORM.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
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>