1 package org.kuali.student.enrollment.lpr.dao;
2
3 import org.springframework.orm.jpa.JpaTemplate;
4 import org.springframework.orm.jpa.support.JpaDaoSupport;
5
6 import javax.persistence.EntityManager;
7 import javax.persistence.PersistenceContext;
8 import javax.persistence.PersistenceContextType;
9 import java.io.Serializable;
10 import java.lang.reflect.ParameterizedType;
11 import java.lang.reflect.Type;
12 import java.util.ArrayList;
13 import java.util.List;
14
15
16
17
18 public class GenericEntityDao<T> implements EntityDao<T> {
19
20
21
22
23 protected Class<T> entityClass;
24
25 @PersistenceContext
26 protected EntityManager em;
27
28 public GenericEntityDao() {
29 entityClass = getEntityClass();
30 }
31
32 @Override
33 public T find(Serializable primaryKey) {
34 return em.find(entityClass, primaryKey);
35 }
36
37 @Override
38 public List<T> findByIds(List<? extends Serializable> primaryKeys) {
39 List<T> resultList = new ArrayList<T>();
40 for (Serializable primaryKey : primaryKeys) {
41 resultList.add(find(primaryKey));
42 }
43 return resultList;
44 }
45
46 @Override
47 @SuppressWarnings("unchecked")
48 public List<T> findAll() {
49 return (List<T>) em.createQuery("from " + entityClass.getSimpleName()).getResultList();
50 }
51
52 @Override
53 public void persist(T entity) {
54 em.persist(entity);
55 }
56
57 @Override
58 public void update(T entity) {
59 em.refresh(entity);
60 }
61
62 @Override
63 public void remove(T entity) {
64 em.remove(entity);
65 }
66
67 @Override
68 public <T> T merge(T entity) {
69 return em.merge(entity);
70 }
71
72 @SuppressWarnings("unchecked")
73 protected <K extends T> Class<K> getEntityClass() {
74 if (entityClass == null) {
75 entityClass = (Class<T>) getEntityType(this);
76 }
77 return (Class<K>) entityClass;
78 }
79
80 private Type getEntityType(Object object) {
81 Type type = object.getClass().getGenericSuperclass();
82 if (type instanceof ParameterizedType) {
83 ParameterizedType paramType = (ParameterizedType) type;
84 Type result = paramType.getActualTypeArguments()[0];
85 return result;
86 } else {
87 throw new IllegalArgumentException("Could not guess entity type by reflection.");
88 }
89 }
90
91 public void setEm(EntityManager em) {
92 this.em = em;
93 }
94 }