View Javadoc

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