1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.joda.time.contrib.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 import org.hibernate.HibernateException;
25 import org.hibernate.type.StandardBasicTypes;
26 import org.hibernate.usertype.UserType;
27 import org.joda.time.DateTime;
28 import org.joda.time.DateTimeZone;
29
30
31
32
33
34
35
36 public class PersistentDateTimeTZ implements UserType, Serializable {
37
38 public static final PersistentDateTimeTZ INSTANCE = new PersistentDateTimeTZ();
39
40 private static final int[] SQL_TYPES = new int[] { Types.TIMESTAMP, Types.VARCHAR, };
41
42 public int[] sqlTypes() {
43 return SQL_TYPES;
44 }
45
46 public Class returnedClass() {
47 return DateTime.class;
48 }
49
50 public boolean equals(Object x, Object y) throws HibernateException {
51 if (x == y) {
52 return true;
53 }
54 if (x == null || y == null) {
55 return false;
56 }
57 DateTime dtx = (DateTime) x;
58 DateTime dty = (DateTime) y;
59 return dtx.equals(dty);
60 }
61
62 public int hashCode(Object object) throws HibernateException {
63 return object.hashCode();
64 }
65
66 public Object nullSafeGet(ResultSet resultSet, String[] strings, Object object) throws HibernateException, SQLException {
67 Object timestamp = StandardBasicTypes.TIMESTAMP.nullSafeGet(resultSet, strings[0]);
68 Object timezone = StandardBasicTypes.STRING.nullSafeGet(resultSet, strings[1]);
69 if (timestamp == null || timezone == null) {
70 return null;
71 }
72 return new DateTime(timestamp, DateTimeZone.forID(timezone.toString()));
73 }
74
75 public void nullSafeSet(PreparedStatement preparedStatement, Object value, int index) throws HibernateException, SQLException {
76 if (value == null) {
77 StandardBasicTypes.TIMESTAMP.nullSafeSet(preparedStatement, null, index);
78 StandardBasicTypes.STRING.nullSafeSet(preparedStatement, null, index + 1);
79 } else {
80 DateTime dt = (DateTime) value;
81 StandardBasicTypes.TIMESTAMP.nullSafeSet(preparedStatement, dt.toDate(), index);
82 StandardBasicTypes.STRING.nullSafeSet(preparedStatement, dt.getZone().getID(), index + 1);
83 }
84 }
85
86 public Object deepCopy(Object value) throws HibernateException {
87 return value;
88 }
89
90 public boolean isMutable() {
91 return false;
92 }
93
94 public Serializable disassemble(Object value) throws HibernateException {
95 return (Serializable) value;
96 }
97
98 public Object assemble(Serializable cached, Object value) throws HibernateException {
99 return cached;
100 }
101
102 public Object replace(Object original, Object target, Object owner) throws HibernateException {
103 return original;
104 }
105
106 }