1 package org.jbpm.bpel.hibernate; 2 3 import java.io.Serializable; 4 import java.sql.PreparedStatement; 5 import java.sql.ResultSet; 6 import java.sql.SQLException; 7 import java.sql.Types; 8 import java.util.Properties; 9 10 import org.apache.commons.lang.enum.EnumUtils; 11 import org.hibernate.Hibernate; 12 import org.hibernate.HibernateException; 13 import org.hibernate.usertype.ParameterizedType; 14 import org.hibernate.usertype.UserType; 15 16 20 public class EnumType implements UserType, ParameterizedType { 21 22 static final int[] SQLTYPES = new int[]{Types.SMALLINT}; 23 private Class enumClass; 24 25 public boolean equals(Object o1, Object o2) { return (o1==o2); } 26 public int hashCode(Object o) throws HibernateException { return o.hashCode(); } 27 public Object deepCopy(Object o) throws HibernateException { return o; } 28 public boolean isMutable() { return false; } 29 public Serializable disassemble(Object o) throws HibernateException { return (Serializable) o; } 30 public Object assemble(Serializable s, Object o) throws HibernateException { return s; } 31 public Object replace(Object original, Object target, Object owner) { return target; } 32 public int[] sqlTypes() { return SQLTYPES; } 33 34 35 public Object nullSafeGet(ResultSet rs, String[] names, Object owner) 36 throws HibernateException, SQLException { 37 int enumCode = ((Integer) Hibernate.INTEGER.nullSafeGet(rs, names[0])).intValue(); 38 39 if(enumCode < 0) return null; 40 return EnumUtils.getEnumList(enumClass).get(enumCode); 41 } 42 43 44 public void nullSafeSet(PreparedStatement st, Object value, int index) 45 throws HibernateException, SQLException { 46 if ((value != null) && !returnedClass().isAssignableFrom(value.getClass())) { 48 throw new IllegalArgumentException("Received value is not a[" + 49 returnedClass().getName() + "] but [" + value.getClass() + "]"); 50 } 51 52 st.setInt(index, EnumUtils.getEnumList(enumClass).indexOf(value)); 54 } 55 56 public Class returnedClass() { 57 return enumClass; 58 } 59 60 public void setParameterValues(Properties parameters) throws HibernateException { 61 try { 62 enumClass = Class.forName((String) parameters.get("class")); 63 } catch (ClassNotFoundException e) { 64 throw new HibernateException(e); 65 } 66 } 67 } 68 | Popular Tags |