2 * Copyright 2005-2010 the original author or authors.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
16 package org.wamblee.persistence;
18 import java.io.Serializable;
19 import java.lang.annotation.Annotation;
20 import java.lang.reflect.Field;
21 import java.lang.reflect.Method;
22 import java.util.List;
24 import java.util.concurrent.ConcurrentHashMap;
26 import javax.persistence.Id;
27 import javax.persistence.Version;
29 import org.wamblee.reflection.ReflectionUtils;
32 * Factory which creates a {@link Persistent} object for a given entity for
33 * interfacing with the primary key and version of the entity.
35 * This utility only treats primary keys and fields that are annotated with @Id
36 * and @Version. In case ORM files are used for the definition of primary key
37 * and or version, then those fields are ignored.
39 * @author Erik Brakkee
42 public class PersistentFactory {
45 * Cache of a mapping of class names to entity accessors.
47 private static Map<String, EntityAccessor> CACHE = new ConcurrentHashMap<String, EntityAccessor>();
49 static interface Accessor<T> {
50 void set(Object aEntity, T aValue);
52 T get(Object aEntity);
55 static class FieldAccessor<T> implements Accessor<T> {
58 public FieldAccessor(Field aField) {
60 field.setAccessible(true);
64 public T get(Object aEntity) {
66 T value = (T) field.get(aEntity);
68 } catch (Exception e) {
69 throw new RuntimeException(e);
74 public void set(Object aEntity, T aValue) {
76 field.set(aEntity, aValue);
77 } catch (IllegalAccessException e) {
78 throw new RuntimeException(e.getMessage(), e);
82 public Field getField() {
87 static class PropertyAccessor<T> implements Accessor<T> {
88 private Method getter;
89 private Method setter;
91 public PropertyAccessor(Method aGetter, Method aSetter) {
94 getter.setAccessible(true);
95 setter.setAccessible(true);
99 public T get(Object aEntity) {
101 return (T) getter.invoke(aEntity);
102 } catch (Exception e) {
103 throw new RuntimeException(e);
108 public void set(Object aEntity, T aValue) {
110 setter.invoke(aEntity, aValue);
111 } catch (Exception e) {
112 throw new RuntimeException(e);
116 public Method getGetter() {
120 public Method getSetter() {
125 static class EntityAccessor {
127 private Accessor version;
129 public EntityAccessor(Accessor<?> aPk, Accessor<?> aVersion) {
134 public Accessor getPk() {
138 public Accessor getVersion() {
143 public static class EntityObjectAccessor implements Persistent {
144 private EntityAccessor accessor;
145 private Object entity;
147 public EntityObjectAccessor(Object aEntity, EntityAccessor aAccessor) {
148 accessor = aAccessor;
152 public EntityAccessor getAccessor() {
157 public Serializable getPrimaryKey() {
158 if (accessor == null || accessor.getPk() == null) {
161 return (Serializable) accessor.getPk().get(entity);
165 public void setPrimaryKey(Serializable aKey) {
166 if (accessor == null || accessor.getPk() == null) {
169 accessor.getPk().set(entity, aKey);
173 public Number getPersistedVersion() {
174 if (accessor == null || accessor.getVersion() == null) {
177 return (Number) accessor.getVersion().get(entity);
181 public void setPersistedVersion(Number aVersion) {
182 if (accessor == null || accessor.getVersion() == null) {
185 accessor.getVersion().set(entity, aVersion);
190 * Create the entity accessor for a given class or returns a cached instance
191 * if one already exists.
195 * @return Entity accessor for the given class or null of the given object
198 public static EntityAccessor createEntityAccessor(Class aClass) {
199 EntityAccessor accessor = CACHE.get(aClass.getName());
200 if (accessor == null) {
201 accessor = analyse(aClass);
202 if (accessor != null) {
203 CACHE.put(aClass.getName(), accessor);
209 private static EntityAccessor analyse(Class aClass) {
210 Accessor<Serializable> pk = analyse(aClass, Id.class);
211 Accessor<Integer> version = analyse(aClass, Version.class);
212 if (pk != null || version != null) {
213 return new EntityAccessor(pk, version);
219 * Returns the accessor for a given annotation.
224 * Annotation that must be present.
225 * @return Accessor to use or null if the annotation is not present.
227 private static Accessor analyse(Class aClass,
228 Class<? extends Annotation> aAnnotation) {
229 List<Field> fields = ReflectionUtils.getAllFields(aClass);
230 for (Field field : fields) {
231 if (field.isAnnotationPresent(aAnnotation)) {
232 return new FieldAccessor(field);
235 List<Method> methods = ReflectionUtils.getAllMethods(aClass,
237 for (Method method : methods) {
238 if (method.isAnnotationPresent(aAnnotation)) {
239 String setterName = null;
240 if (method.getName().startsWith("get")) {
241 setterName = method.getName().replaceFirst("get", "set");
242 } else if (method.getName().startsWith("is")) {
243 setterName = method.getName().replaceFirst("is", "set");
246 Class returnType = method.getReturnType();
247 Method setter = method.getDeclaringClass()
248 .getDeclaredMethod(setterName, returnType);
249 return new PropertyAccessor(method, setter);
250 } catch (NoSuchMethodException e) {
251 throw new RuntimeException("Error obtaining setter for " +
252 method.getName() + " in class " + aClass.getName(), e);
260 * Creates the {@link Persistent} wrapper for interfacing with primary key
261 * and version of the entity.
265 * @return Persistent object or null if this is not an entity.
267 public static Persistent create(Object aEntity) {
268 EntityAccessor accessor = createEntityAccessor(aEntity.getClass());
269 if (accessor == null) {
272 return new EntityObjectAccessor(aEntity, accessor);