001    package com.khubla.pragmatach.plugin.openjpa;
002    
003    import java.io.Serializable;
004    import java.util.HashMap;
005    import java.util.List;
006    import java.util.Map;
007    import java.util.Set;
008    
009    import javax.persistence.Entity;
010    import javax.persistence.EntityManager;
011    import javax.persistence.EntityManagerFactory;
012    import javax.persistence.EntityTransaction;
013    import javax.persistence.Persistence;
014    import javax.persistence.criteria.CriteriaBuilder;
015    import javax.persistence.criteria.CriteriaQuery;
016    
017    import com.khubla.pragmatach.framework.api.PragmatachException;
018    import com.khubla.pragmatach.framework.application.Application;
019    import com.khubla.pragmatach.framework.dao.AbstractDAO;
020    import com.khubla.pragmatach.framework.scanner.AnnotationScanner;
021    
022    /**
023     * @author tome
024     */
025    public class OpenJPADAO<T, I extends Serializable> extends AbstractDAO<T, I> {
026       /**
027        * the annotation scanner will have run; we can just query for annotated classes
028        */
029       protected static Set<Class<?>> getEntityClasses() throws PragmatachException {
030          try {
031             return AnnotationScanner.getAllClasses(Entity.class);
032          } catch (final Exception e) {
033             throw new PragmatachException("Exception in getAnnotatedClasses", e);
034          }
035       }
036    
037       /**
038        * create the EntityManager
039        * <p>
040        * http://openjpa.apache.org/builds/2.1.1/apache-openjpa/docs/ref_guide_conf.html
041        * </p>
042        */
043       private static EntityManager getEntityManager() {
044          try {
045             /*
046              * get classes
047              */
048             String classesList = "";
049             final Set<Class<?>> entityClasses = getEntityClasses();
050             if (null != entityClasses) {
051                boolean first = true;
052                for (final Class<?> clazz : entityClasses) {
053                   if (first) {
054                      first = false;
055                   } else {
056                      classesList += ";";
057                   }
058                   classesList += clazz.getName();
059                }
060             }
061             /*
062              * set up the properties
063              */
064             final Map<String, String> properties = new HashMap<String, String>();
065             final String dataSource = Application.getConfiguration().getParameter("openjpa.ConnectionFactoryName");
066             if ((null != dataSource) && (dataSource.length() > 0)) {
067                properties.put("openjpa.ConnectionFactoryName", dataSource);
068             } else {
069                properties.put("openjpa.ConnectionURL", Application.getConfiguration().getParameter("openjpa.ConnectionURL"));
070                properties.put("openjpa.ConnectionDriverName", Application.getConfiguration().getParameter("openjpa.ConnectionDriverName"));
071                properties.put("openjpa.ConnectionUserName", Application.getConfiguration().getParameter("openjpa.ConnectionUserName"));
072                properties.put("openjpa.ConnectionPassword", Application.getConfiguration().getParameter("openjpa.ConnectionPassword"));
073             }
074             /*
075              * more properties
076              */
077             properties.put("openjpa.jdbc.SynchronizeMappings", Application.getConfiguration().getParameter("openjpa.jdbc.SynchronizeMappings"));
078             properties.put("openjpa.MetaDataFactory", "jpa(Types=" + classesList + ")");
079             properties.put("openjpa.RuntimeUnenhancedClasses", "supported");
080             /*
081              * EntityManagerFactory
082              */
083             final EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("Pragmatach", properties);
084             /*
085              * the EntityManager
086              */
087             return entityManagerFactory.createEntityManager();
088          } catch (final Exception e) {
089             throw new ExceptionInInitializerError(e);
090          }
091       }
092    
093       /**
094        * EntityManager
095        */
096       private static EntityManager entityManager = getEntityManager();
097       /**
098        * the type
099        */
100       private final Class<T> typeClazz;
101       /**
102        * the identifier
103        */
104       private final Class<I> identifierClazz;
105    
106       public OpenJPADAO(Class<T> typeClazz, Class<I> identifierClazz) {
107          this.typeClazz = typeClazz;
108          this.identifierClazz = identifierClazz;
109       }
110    
111       @Override
112       public long count() throws PragmatachException {
113          final CriteriaBuilder qb = entityManager.getCriteriaBuilder();
114          final CriteriaQuery<Long> cq = qb.createQuery(Long.class);
115          cq.select(qb.count(cq.from(this.typeClazz)));
116          return entityManager.createQuery(cq).getSingleResult();
117       }
118    
119       /**
120        * delete
121        */
122       public void delete(T t) throws PragmatachException {
123          EntityTransaction entityTransaction = null;
124          try {
125             entityTransaction = entityManager.getTransaction();
126             entityTransaction.begin();
127             entityManager.remove(t);
128             entityTransaction.commit();
129          } catch (final Exception e) {
130             if (null != entityTransaction) {
131                entityTransaction.rollback();
132             }
133             throw new PragmatachException("Exception in delete", e);
134          }
135       }
136    
137       /**
138        * delete
139        */
140       public void deletebyId(I i) throws PragmatachException {
141          EntityTransaction entityTransaction = null;
142          try {
143             entityTransaction = entityManager.getTransaction();
144             entityTransaction.begin();
145             final T t = entityManager.find(typeClazz, i);
146             if (null != t) {
147                entityManager.remove(t);
148             }
149             entityTransaction.commit();
150          } catch (final Exception e) {
151             if (null != entityTransaction) {
152                entityTransaction.rollback();
153             }
154             throw new PragmatachException("Exception in deletebyId", e);
155          }
156       }
157    
158       /**
159        * get criteria builder
160        */
161       public CriteriaQuery<T> find() throws PragmatachException {
162          return entityManager.getCriteriaBuilder().createQuery(this.typeClazz);
163       }
164    
165       /**
166        * find by id
167        */
168       public T findById(I i) throws PragmatachException {
169          try {
170             return entityManager.find(typeClazz, i);
171          } catch (final Exception e) {
172             throw new PragmatachException("Exception in findById", e);
173          }
174       }
175    
176       /**
177        * findall
178        */
179       public List<T> getAll() throws PragmatachException {
180          final CriteriaQuery<T> criteria = entityManager.getCriteriaBuilder().createQuery(typeClazz);
181          criteria.select(criteria.from(typeClazz));
182          return entityManager.createQuery(criteria).getResultList();
183       }
184    
185       @Override
186       public List<T> getAll(int start, int count) throws PragmatachException {
187          return entityManager.createQuery(this.find()).setFirstResult(start).setMaxResults(count).getResultList();
188       }
189    
190       public Class<I> getIdentifierClazz() {
191          return identifierClazz;
192       }
193    
194       public Class<T> getTypeClazz() {
195          return typeClazz;
196       }
197    
198       @Override
199       public void reloadConfig() {
200          entityManager = getEntityManager();
201       }
202    
203       /**
204        * save object
205        */
206       public void save(T t) throws PragmatachException {
207          EntityTransaction entityTransaction = null;
208          try {
209             entityTransaction = entityManager.getTransaction();
210             entityTransaction.begin();
211             entityManager.persist(t);
212             entityTransaction.commit();
213          } catch (final Exception e) {
214             if (null != entityTransaction) {
215                entityTransaction.rollback();
216             }
217             throw new PragmatachException("Exception in save", e);
218          }
219       }
220    
221       /**
222        * update object
223        */
224       public void update(T t) throws PragmatachException {
225          EntityTransaction entityTransaction = null;
226          try {
227             entityTransaction = entityManager.getTransaction();
228             entityTransaction.begin();
229             entityManager.merge(t);
230             entityTransaction.commit();
231          } catch (final Exception e) {
232             if (null != entityTransaction) {
233                entityTransaction.rollback();
234             }
235             throw new PragmatachException("Exception in update", e);
236          }
237       }
238    }