00001 package cedar.hepdata.db; 00002 00003 import java.io.Serializable; 00004 import java.sql.PreparedStatement; 00005 import java.sql.ResultSet; 00006 import java.sql.SQLException; 00007 import java.sql.Types; 00008 import org.hibernate.HibernateException; 00009 import org.hibernate.usertype.UserType; 00010 00011 public class EnumUserType<E extends Enum<E>> implements UserType { 00012 private Class<E> clazz = null; 00013 protected EnumUserType(Class<E> c) { 00014 this.clazz = c; 00015 } 00016 00017 private static final int[] SQL_TYPES = {Types.VARCHAR}; 00018 public int[] sqlTypes() { 00019 return SQL_TYPES; 00020 } 00021 00022 public Class returnedClass() { 00023 return clazz; 00024 } 00025 00026 public Object nullSafeGet(ResultSet resultSet, String[] names, Object owner) throws HibernateException, SQLException { 00027 String name = resultSet.getString(names[0]); 00028 E result = null; 00029 if (!resultSet.wasNull()) { 00030 result = Enum.valueOf(clazz, name); 00031 } 00032 return result; 00033 } 00034 00035 public void nullSafeSet(PreparedStatement preparedStatement, Object value, int index) throws HibernateException, SQLException { 00036 if (null == value) { 00037 preparedStatement.setNull(index, Types.VARCHAR); 00038 } else { 00039 preparedStatement.setString(index, ((Enum)value).name()); 00040 } 00041 } 00042 00043 public Object deepCopy(Object value) throws HibernateException{ 00044 return value; 00045 } 00046 00047 public boolean isMutable() { 00048 return false; 00049 } 00050 00051 public Object assemble(Serializable cached, Object owner) throws HibernateException { 00052 return cached; 00053 } 00054 00055 public Serializable disassemble(Object value) throws HibernateException { 00056 return (Serializable)value; 00057 } 00058 00059 public Object replace(Object original, Object target, Object owner) throws HibernateException { 00060 return original; 00061 } 00062 public int hashCode(Object x) throws HibernateException { 00063 return x.hashCode(); 00064 } 00065 public boolean equals(Object x, Object y) throws HibernateException { 00066 if (x == y) 00067 return true; 00068 if (null == x || null == y) 00069 return false; 00070 return x.equals(y); 00071 } 00072 }