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   
10  /**
11   * Custom Hibernate UserType to persist a Java 5 enum constant as a VARCHAR
12   * using its name.
13   * <p/>
14   * <p>Based on the original class by Gavin King
15   * (http://www.hibernate.org/272.html). </p>
16   *
17   * @author johnny
18   */
19  public class EnumNameUserType extends AbstractEnumUserType {
20  
21      private static final int[] SQL_TYPES = {Types.VARCHAR};
22  
23      /**
24       * Default constructor, required by Hibernate.
25       */
26      public EnumNameUserType() {
27      }
28  
29      @SuppressWarnings("unchecked")
30      public Object nullSafeGet(ResultSet rs, String[] names, Object owner)
31              throws HibernateException, SQLException {
32          final String name = rs.getString(names[0]);
33  
34          return rs.wasNull() ? null : Enum.valueOf(this.enumClass, name);
35      }
36  
37      public void nullSafeSet(PreparedStatement st, Object value, int index)
38              throws HibernateException, SQLException {
39          if (value == null) {
40              st.setNull(index, Types.VARCHAR);
41          } else {
42              st.setString(index, ((Enum<?>) value).name());
43          }
44      }
45  
46      public int[] sqlTypes() {
47          return SQL_TYPES;
48      }
49  
50      public String objectToSQLString(Object value) {
51          return '\'' + ((Enum<?>) value).name() + '\'';
52      }
53  
54      public String toXMLString(Object value) {
55          return ((Enum<?>) value).name();
56      }
57  
58      @SuppressWarnings("unchecked")
59      public Object fromXMLString(String xmlValue) {
60          return Enum.valueOf(this.enumClass, xmlValue);
61      }
62  
63  }