1 package org.hibernate.ce.auction.persistence; 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.hibernate.HibernateException; 11 import org.hibernate.usertype.EnhancedUserType; 12 import org.hibernate.usertype.ParameterizedType; 13 14 23 public class EnumUserType implements EnhancedUserType, ParameterizedType { 24 25 private Class <Enum > enumClass; 26 27 public void setParameterValues(Properties parameters) { 28 String enumClassName = parameters.getProperty("enumClassName"); 29 try { 30 enumClass = (Class <Enum >) Class.forName(enumClassName); 31 } 32 catch (ClassNotFoundException cnfe) { 33 throw new HibernateException("Enum class not found", cnfe); 34 } 35 } 36 37 public Object assemble(Serializable cached, Object owner) 38 throws HibernateException { 39 return cached; 40 } 41 42 public Object deepCopy(Object value) throws HibernateException { 43 return value; 44 } 45 46 public Serializable disassemble(Object value) throws HibernateException { 47 return (Enum ) value; 48 } 49 50 public boolean equals(Object x, Object y) throws HibernateException { 51 return x==y; 52 } 53 54 public int hashCode(Object x) throws HibernateException { 55 return x.hashCode(); 56 } 57 58 public boolean isMutable() { 59 return false; 60 } 61 62 public Object nullSafeGet(ResultSet rs, String [] names, Object owner) 63 throws HibernateException, SQLException { 64 String name = rs.getString( names[0] ); 65 return rs.wasNull() ? null : Enum.valueOf(enumClass, name); 66 } 67 68 public void nullSafeSet(PreparedStatement st, Object value, int index) 69 throws HibernateException, SQLException { 70 if (value==null) { 71 st.setNull(index, Types.VARCHAR); 72 } 73 else { 74 st.setString( index, ( (Enum ) value ).name() ); 75 } 76 } 77 78 public Object replace(Object original, Object target, Object owner) 79 throws HibernateException { 80 return original; 81 } 82 83 public Class returnedClass() { 84 return enumClass; 85 } 86 87 public int[] sqlTypes() { 88 return new int[] { Types.VARCHAR }; 89 } 90 91 public Object fromXMLString(String xmlValue) { 92 return Enum.valueOf(enumClass, xmlValue); 93 } 94 95 public String objectToSQLString(Object value) { 96 return '\'' + ( (Enum ) value ).name() + '\''; 97 } 98 99 public String toXMLString(Object value) { 100 return ( (Enum ) value ).name(); 101 } 102 103 } 104 | Popular Tags |