View Javadoc
1   package org.itracker.persistence.dao;
2   
3   import org.hibernate.HibernateException;
4   
5   import java.sql.PreparedStatement;
6   import java.sql.ResultSet;
7   import java.sql.SQLException;
8   import java.sql.Types;
9   import java.util.Properties;
10  
11  /**
12   * Custom Hibernate UserType to persist a Java 5 enum constant as an INTEGER
13   * using its ordinal position.
14   * <p/>
15   * <p>Beware that the enum.ordinal() returns a is zero based that changes
16   * if the position of the enum members change! </p>
17   *
18   * @author johnny
19   */
20  public final class EnumOrdinalUserType extends AbstractEnumUserType {
21  
22      private static final int[] SQL_TYPES = {Types.SMALLINT};
23  
24      /**
25       * Enum members, in the order they where declared.
26       */
27      @SuppressWarnings("unchecked")
28      private Enum[] enumValues;
29  
30      /**
31       * Default constructor, required by Hibernate.
32       */
33      public EnumOrdinalUserType() {
34      }
35  
36      public void setParameterValues(Properties parameters) {
37          super.setParameterValues(parameters);
38          this.enumValues = this.enumClass.getEnumConstants();
39      }
40  
41      public Object nullSafeGet(ResultSet rs, String[] names,
42                                Object owner) throws HibernateException, SQLException {
43          final int ordinal = rs.getInt(names[0]);
44  
45          return rs.wasNull() ? null : this.enumValues[ordinal];
46      }
47  
48      public void nullSafeSet(PreparedStatement stmt, Object value,
49                              int index) throws HibernateException, SQLException {
50          if (value == null) {
51              stmt.setNull(index, Types.INTEGER);
52          } else {
53              stmt.setInt(index, ((Enum<?>) value).ordinal());
54          }
55      }
56  
57      public int[] sqlTypes() {
58          return SQL_TYPES;
59      }
60  
61      public String objectToSQLString(Object value) {
62          return Integer.toString(((Enum<?>) value).ordinal());
63      }
64  
65      public String toXMLString(Object value) {
66          return objectToSQLString(value);
67      }
68  
69      public Object fromXMLString(String xmlValue) {
70          final int ordinal;
71  
72          try {
73              ordinal = Integer.parseInt(xmlValue);
74          } catch (NumberFormatException ex) {
75              throw new HibernateException(ex);
76          }
77          return this.enumValues[ordinal];
78      }
79  
80  }