1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package ch.elca.el4j.services.persistence.generic.dto;
19
20 import javax.persistence.Column;
21 import javax.persistence.GeneratedValue;
22 import javax.persistence.GenerationType;
23 import javax.persistence.Id;
24 import javax.persistence.MappedSuperclass;
25 import javax.persistence.Transient;
26
27 import org.slf4j.Logger;
28 import org.slf4j.LoggerFactory;
29
30 import ch.elca.el4j.util.codingsupport.Reject;
31
32
33
34
35
36
37
38
39
40
41 @MappedSuperclass
42 public abstract class AbstractIntKeyIntOptimisticLockingDto
43 extends AbstractIntOptimisticLockingDto
44 implements PrimaryKeyOptimisticLockingObject {
45
46
47
48
49 private static Logger s_logger = LoggerFactory.getLogger(AbstractIntKeyIntOptimisticLockingDto.class);
50
51
52
53
54 private int m_key;
55
56
57
58
59 private boolean m_keyNew = true;
60
61
62
63
64 private boolean m_transientHashCodeLeaked = false;
65
66
67
68
69 @Id @GeneratedValue(strategy = GenerationType.AUTO,
70 generator = "keyid_generator")
71 @Column(name = "KEYID")
72 public int getKey() {
73 return m_key;
74 }
75
76
77
78
79 @Transient
80 public Object getKeyAsObject() {
81 return isKeyNew() ? null : Integer.valueOf(getKey());
82 }
83
84
85
86
87 public void setKey(int key) {
88 m_key = key;
89 m_keyNew = false;
90 }
91
92
93
94
95
96
97
98 public void setKey(Object keyObject) {
99 Reject.ifNull(keyObject);
100 Reject.ifNotAssignableTo(keyObject, Number.class);
101 int key = ((Number) keyObject).intValue();
102 setKey(key);
103 }
104
105
106
107
108
109 @Transient
110 public boolean isKeyNew() {
111 return m_keyNew;
112 }
113
114
115
116
117 public int hashCode() {
118 if (m_keyNew) {
119 m_transientHashCodeLeaked = true;
120 return super.hashCode();
121 } else {
122 if (m_transientHashCodeLeaked) {
123 s_logger.error("hashCode() has be called once on transient state and once on persistent state "
124 + "of object '" + this.toString() + "' (" + getClass().toString() + "). "
125 + "This can happen if you insert a transient object into a collection and persist them afterwards. "
126 + "Save the objects before you insert them into a collection!");
127 }
128 return m_key;
129 }
130 }
131
132
133
134
135 public boolean equals(Object obj) {
136 if (this == obj) {
137 return true;
138 }
139
140
141
142
143 if (obj instanceof AbstractIntKeyIntOptimisticLockingDto) {
144 final AbstractIntKeyIntOptimisticLockingDto other = (AbstractIntKeyIntOptimisticLockingDto) obj;
145 if (!isKeyNew() && !other.isKeyNew()) {
146 return getKey() == other.getKey() && getClass() == other.getClass();
147 }
148 }
149 return false;
150 }
151
152
153
154
155
156 public void resetNew() {
157 m_keyNew = true;
158 }
159
160
161
162
163
164
165 public void useGeneratedKey() { }
166 }