1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.acegisecurity.domain.hibernate;
17
18 import java.io.Serializable;
19 import java.sql.PreparedStatement;
20 import java.sql.ResultSet;
21 import java.sql.SQLException;
22 import java.sql.Types;
23
24
25 import org.hibernate.HibernateException;
26 import org.hibernate.usertype.UserType;
27
28 /***
29 * Java 1.5 <code>enum</code>eration compatible Hibernate 3 <code>UserType</code>.
30 *
31 * @author Ben Alex
32 * @version $Id: EnumUserType.java,v 1.2 2005/11/17 00:55:49 benalex Exp $
33 */
34 public class EnumUserType<E extends Enum<E>> implements UserType {
35 private Class<E> clazz = null;
36 protected EnumUserType(Class<E> c) {
37 this.clazz = c;
38 }
39
40 private static final int[] SQL_TYPES = {Types.VARCHAR};
41 public int[] sqlTypes() {
42 return SQL_TYPES;
43 }
44
45 public Class returnedClass() {
46 return clazz;
47 }
48
49 public Object nullSafeGet(ResultSet resultSet, String[] names, Object owner) throws HibernateException, SQLException {
50 String name = resultSet.getString(names[0]);
51 E result = null;
52 if (!resultSet.wasNull()) {
53 result = Enum.valueOf(clazz, name);
54 }
55 return result;
56 }
57
58 public void nullSafeSet(PreparedStatement preparedStatement, Object value, int index) throws HibernateException, SQLException {
59 if (null == value) {
60 preparedStatement.setNull(index, Types.VARCHAR);
61 } else {
62 preparedStatement.setString(index, ((Enum)value).name());
63 }
64 }
65
66 public Object deepCopy(Object value) throws HibernateException{
67 return value;
68 }
69
70 public boolean isMutable() {
71 return false;
72 }
73
74 public Object assemble(Serializable cached, Object owner) throws HibernateException {
75 return cached;
76 }
77
78 public Serializable disassemble(Object value) throws HibernateException {
79 return (Serializable)value;
80 }
81
82 public Object replace(Object original, Object target, Object owner) throws HibernateException {
83 return original;
84 }
85 public int hashCode(Object x) throws HibernateException {
86 return x.hashCode();
87 }
88 public boolean equals(Object x, Object y) throws HibernateException {
89 if (x == y)
90 return true;
91 if (null == x || null == y)
92 return false;
93 return x.equals(y);
94 }
95 }