View Javadoc

1   package nl.gridshore.samples.training.dataaccess.jpa;
2   
3   import nl.gridshore.samples.training.dataaccess.BaseDao;
4   import nl.gridshore.samples.training.domain.BaseDomain;
5   import org.springframework.orm.ObjectRetrievalFailureException;
6   import org.springframework.transaction.annotation.Transactional;
7   
8   import javax.persistence.PersistenceContext;
9   import javax.persistence.EntityManager;
10  import javax.persistence.Query;
11  import java.util.List;
12  
13  /**
14   * Created by IntelliJ IDEA.
15   * User: jettro
16   * Date: Jan 20, 2008
17   * Time: 5:03:11 PM
18   * Standard implementation for the base interface data access objects
19   */
20  public class BaseDaoJpa<T extends BaseDomain> implements BaseDao<T> {
21      @PersistenceContext
22      private EntityManager entityManager;
23      private Class<T> prototype;
24      private String entityName;
25  
26      public BaseDaoJpa(Class<T> prototype, String entityName) {
27          this.prototype = prototype;
28          this.entityName = entityName;
29      }
30      
31      public T save(T entity) {
32          if (entity.getId() != null) {
33              entityManager.merge(entity);
34          } else {
35              entityManager.persist(entity);
36          }
37          return entity;
38      }
39  
40      public T loadById(Long entityId) throws ObjectRetrievalFailureException {
41          T entity = entityManager.find(prototype, entityId);
42          if (entity == null) {
43              throw new ObjectRetrievalFailureException(prototype, entityId);
44          }
45          return entity;
46      }
47  
48      public List<T> loadAll() {
49          Query query = entityManager.createQuery("select obj from " + entityName + " obj order by obj.id");
50          //noinspection unchecked
51          return query.getResultList();
52      }
53  
54      public void delete(final T entity) {
55          T loadedEntity = loadById(entity.getId());
56          entityManager.remove(loadedEntity);
57      }
58  
59      protected final T newPrototype(Class<T> cl) throws IllegalArgumentException {
60          try {
61              return cl.newInstance();
62          } catch (Exception e) {
63              throw new IllegalArgumentException(e);
64          }
65      }
66  
67      public EntityManager getEntityManager() {
68          return entityManager;
69      }
70  }