| 1 | package info.ahlberg.spring; |
| 2 | |
| 3 | import java.io.Serializable; |
| 4 | import java.lang.reflect.ParameterizedType; |
| 5 | import java.util.List; |
| 6 | |
| 7 | import javax.persistence.EntityManager; |
| 8 | import javax.persistence.PersistenceContext; |
| 9 | |
| 10 | public abstract class GenericDAOWithJPA<T, ID extends Serializable> implements GenericDAO<T, ID> { |
| 11 | |
| 12 | private Class<T> persistentClass; |
| 13 | |
| 14 | protected EntityManager entityManager; |
| 15 | |
| 16 | @SuppressWarnings("unchecked") |
| 17 | public GenericDAOWithJPA() { |
| 18 | this.persistentClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()) |
| 19 | .getActualTypeArguments()[0]; |
| 20 | } |
| 21 | |
| 22 | @PersistenceContext |
| 23 | public void setEntityManager(EntityManager entityManager) { |
| 24 | this.entityManager = entityManager; |
| 25 | } |
| 26 | |
| 27 | public void flush() { |
| 28 | entityManager.flush(); |
| 29 | } |
| 30 | |
| 31 | public Class<T> getPersistentClass() { |
| 32 | return persistentClass; |
| 33 | } |
| 34 | |
| 35 | public T loadById(ID id) { |
| 36 | if(id == null) { |
| 37 | return null; |
| 38 | } else { |
| 39 | return entityManager.find(persistentClass, id); |
| 40 | } |
| 41 | } |
| 42 | |
| 43 | public void persist(T entity) { |
| 44 | entityManager.persist(entity); |
| 45 | } |
| 46 | |
| 47 | public void update(T entity) { |
| 48 | entityManager.merge(entity); |
| 49 | entityManager.flush(); |
| 50 | } |
| 51 | |
| 52 | public void delete(T entity) { |
| 53 | entityManager.remove(entity); |
| 54 | } |
| 55 | |
| 56 | @SuppressWarnings("unchecked") |
| 57 | public List<T> loadAll() { |
| 58 | return entityManager.createQuery("Select t from " + persistentClass.getSimpleName() + " t") |
| 59 | .setHint("org.hibernate.cacheable", true).getResultList(); |
| 60 | } |
| 61 | } |
| 62 | |