View Javadoc
1   package org.itracker.persistence.dao;
2   
3   import org.hibernate.HibernateException;
4   import org.hibernate.usertype.EnhancedUserType;
5   import org.hibernate.usertype.ParameterizedType;
6   
7   import java.io.Serializable;
8   import java.util.Properties;
9   
10  /**
11   * Base class for custom Hibernate UserTypes to persist a Java 5 enum
12   * constant.
13   * <p/>
14   * <p>This is a parameterized type, which requires the following parameter :
15   * <code>enumClassName</code> = fully qualified name of the enum class
16   * to persist. </p>
17   * <p/>
18   * <p>Example of inline mapping : </p>
19   * <pre>
20   *  <property name='suit'>
21   *   <column name="suit"/>
22   *   <type name="EnumUserType">
23   *     <param name="enumClassName">com.company.project.Suit</param>
24   *   </type>
25   *  </property>
26   * </pre>
27   * <p/>
28   * <p>Example of typedef : </p>
29   * <pre>
30   *  <typedef name="suit" class='EnumUserType'>
31   *    <param name="enumClassName">com.company.project.Suit</param>
32   *  </typedef>
33   *
34   *  <class ...>
35   *   <column name="suit"/>
36   *   <property name='suit' type='suit'/>
37   *  </class>
38   * </pre>
39   *
40   * @author johnny
41   */
42  public abstract class AbstractEnumUserType
43          implements EnhancedUserType, ParameterizedType {
44  
45      @SuppressWarnings("unchecked")
46      protected Class<? extends Enum> enumClass;
47  
48      public AbstractEnumUserType() {
49      }
50  
51      @SuppressWarnings("unchecked")
52      public void setParameterValues(Properties parameters) {
53          String enumClassName = parameters.getProperty("enumClassName");
54          try {
55              this.enumClass = (Class<? extends Enum>) Class.forName(enumClassName);
56          } catch (ClassNotFoundException ex) {
57              throw new HibernateException("Enum class not found", ex);
58          }
59      }
60  
61      public Object assemble(Serializable cached, Object owner)
62              throws HibernateException {
63          return cached;
64      }
65  
66      public Object deepCopy(Object value) throws HibernateException {
67          return value;
68      }
69  
70      public Serializable disassemble(Object value) throws HibernateException {
71          return (Enum<?>) value;
72      }
73  
74      public boolean equals(Object x, Object y) throws HibernateException {
75          return (x == y);
76      }
77  
78      public int hashCode(Object x) throws HibernateException {
79          return x.hashCode();
80      }
81  
82      public boolean isMutable() {
83          return false;
84      }
85  
86      public Object replace(Object original, Object target, Object owner)
87              throws HibernateException {
88          return original;
89      }
90  
91      public Class<?> returnedClass() {
92          return this.enumClass;
93      }
94  
95  }