1 package org.fosstrak.epcis.repository.model;
2
3 import java.io.Serializable;
4 import java.sql.PreparedStatement;
5 import java.sql.ResultSet;
6 import java.sql.SQLException;
7 import java.sql.Types;
8 import java.util.Properties;
9
10 import org.hibernate.HibernateException;
11 import org.hibernate.usertype.EnhancedUserType;
12 import org.hibernate.usertype.ParameterizedType;
13
14
15
16
17
18
19
20 @SuppressWarnings("unchecked")
21 public class EnumUserType implements EnhancedUserType, ParameterizedType {
22
23 private Class<Enum> enumClass;
24
25 public void setParameterValues(Properties parameters) {
26 String enumClassName = parameters.getProperty("enumClassName");
27 try {
28 enumClass = (Class<Enum>) Class.forName(enumClassName);
29 } catch (ClassNotFoundException cnfe) {
30 throw new HibernateException("Enum class not found", cnfe);
31 }
32 }
33
34 public Object assemble(Serializable cached, Object owner) throws HibernateException {
35 return cached;
36 }
37
38 public Object deepCopy(Object value) throws HibernateException {
39 return value;
40 }
41
42 public Serializable disassemble(Object value) throws HibernateException {
43 return (Enum) value;
44 }
45
46 public boolean equals(Object x, Object y) throws HibernateException {
47 return x == y;
48 }
49
50 public int hashCode(Object x) throws HibernateException {
51 return x.hashCode();
52 }
53
54 public boolean isMutable() {
55 return false;
56 }
57
58 public Object nullSafeGet(ResultSet rs, String[] names, Object owner) throws HibernateException, SQLException {
59 String name = rs.getString(names[0]);
60 return rs.wasNull() ? null : Enum.valueOf(enumClass, name);
61 }
62
63 public void nullSafeSet(PreparedStatement st, Object value, int index) throws HibernateException, SQLException {
64 if (value == null) {
65 st.setNull(index, Types.VARCHAR);
66 } else {
67 st.setString(index, ((Enum) value).name());
68 }
69 }
70
71 public Object replace(Object original, Object target, Object owner) throws HibernateException {
72 return original;
73 }
74
75 public Class returnedClass() {
76 return enumClass;
77 }
78
79 public int[] sqlTypes() {
80 return new int[] { Types.VARCHAR };
81 }
82
83 public Object fromXMLString(String xmlValue) {
84 return Enum.valueOf(enumClass, xmlValue);
85 }
86
87 public String objectToSQLString(Object value) {
88 return '\'' + ((Enum) value).name() + '\'';
89 }
90
91 public String toXMLString(Object value) {
92 return ((Enum) value).name();
93 }
94
95 }