1 | package com.ether; |
---|
2 | |
---|
3 | import org.apache.commons.logging.Log; |
---|
4 | import org.apache.commons.logging.LogFactory; |
---|
5 | import org.hibernate.HibernateException; |
---|
6 | |
---|
7 | import java.sql.PreparedStatement; |
---|
8 | import java.sql.ResultSet; |
---|
9 | import java.sql.SQLException; |
---|
10 | import java.sql.Types; |
---|
11 | |
---|
12 | /** |
---|
13 | * The enum user type. |
---|
14 | */ |
---|
15 | public abstract class EnumUserType<E extends Enum<E>> extends SimpleUserType |
---|
16 | { |
---|
17 | protected EnumUserType(final Class<E> clazz) { |
---|
18 | _clazz = clazz; |
---|
19 | } |
---|
20 | |
---|
21 | public int[] sqlTypes() { |
---|
22 | return SQL_TYPES; |
---|
23 | } |
---|
24 | |
---|
25 | public Class returnedClass() { |
---|
26 | return _clazz; |
---|
27 | } |
---|
28 | |
---|
29 | public Object nullSafeGet(final ResultSet resultSet, final String[] names, |
---|
30 | final Object owner) throws HibernateException, SQLException { |
---|
31 | final String name = resultSet.getString(names[0]); |
---|
32 | E result = null; |
---|
33 | if (!resultSet.wasNull()) { |
---|
34 | result = Enum.valueOf(_clazz, name); |
---|
35 | } |
---|
36 | return result; |
---|
37 | } |
---|
38 | |
---|
39 | public void nullSafeSet(final PreparedStatement preparedStatement, |
---|
40 | final Object value, final int index) throws HibernateException, |
---|
41 | SQLException { |
---|
42 | if (null == value) { |
---|
43 | HIBERNATE_TYPE_LOGGER.trace("binding null to parameter: " + index); |
---|
44 | preparedStatement.setNull(index, Types.NVARCHAR); |
---|
45 | } else { |
---|
46 | final String stringValue = ((Enum) value).name(); |
---|
47 | HIBERNATE_TYPE_LOGGER.trace("binding '" + stringValue |
---|
48 | + "' to parameter: " + index); |
---|
49 | preparedStatement.setString(index, stringValue); |
---|
50 | } |
---|
51 | } |
---|
52 | |
---|
53 | private static final Log HIBERNATE_TYPE_LOGGER = LogFactory.getLog(org.hibernate.type.Type.class); |
---|
54 | |
---|
55 | private static final int[] SQL_TYPES = { Types.NVARCHAR }; |
---|
56 | |
---|
57 | private Class<E> _clazz = null; |
---|
58 | } |
---|