001    package com.khubla.pragmatach.plugin.hibernate;
002    
003    import java.io.Serializable;
004    import java.util.List;
005    import java.util.Set;
006    
007    import javax.persistence.Entity;
008    
009    import org.hibernate.Criteria;
010    import org.hibernate.Session;
011    import org.hibernate.SessionFactory;
012    import org.hibernate.Transaction;
013    import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
014    import org.hibernate.cfg.Configuration;
015    import org.hibernate.criterion.Projections;
016    import org.hibernate.service.ServiceRegistry;
017    
018    import com.khubla.pragmatach.framework.api.PragmatachException;
019    import com.khubla.pragmatach.framework.application.Application;
020    import com.khubla.pragmatach.framework.dao.AbstractDAO;
021    import com.khubla.pragmatach.framework.scanner.AnnotationScanner;
022    
023    /**
024     * @author tome
025     */
026    public class HibernateDAO<T, I extends Serializable> extends AbstractDAO<T, I> {
027       public static SessionFactory getSessionFactory() {
028          return sessionFactory;
029       }
030    
031       /**
032        * the type
033        */
034       private final Class<T> typeClazz;
035       /**
036        * the identifier
037        */
038       private final Class<I> identifierClazz;
039       /**
040        * the Hibernate session factory
041        */
042       private static SessionFactory sessionFactory = buildSessionFactory();
043       /**
044        * the Hibernate service registry
045        */
046       private static ServiceRegistry serviceRegistry;
047    
048       private static SessionFactory buildSessionFactory() {
049          try {
050             /*
051              * make config
052              */
053             final Configuration configuration = new Configuration();
054             final String dataSource = Application.getConfiguration().getParameter("hibernate.connection.datasource");
055             if ((null != dataSource) && (dataSource.length() > 0)) {
056                configuration.setProperty("connection.datasource", dataSource);
057             } else {
058                /*
059                 * configure via driver
060                 */
061                configuration.setProperty("hibernate.driver", Application.getConfiguration().getParameter("hibernate.driver"));
062                configuration.setProperty("hibernate.connection.url", Application.getConfiguration().getParameter("hibernate.connection.url"));
063                final String username = Application.getConfiguration().getParameter("hibernate.connection.username");
064                if (username != null) {
065                   configuration.setProperty("hibernate.connection.username", username);
066                }
067                final String password = Application.getConfiguration().getParameter("hibernate.connection.password");
068                if (password != null) {
069                   configuration.setProperty("hibernate.connection.password", password);
070                }
071             }
072             /*
073              * dialect
074              */
075             configuration.setProperty("hibernate.dialect", Application.getConfiguration().getParameter("hibernate.dialect"));
076             /*
077              * generate DDL?
078              */
079             final String autoFlag = Application.getConfiguration().getParameter("hibernate.hbm2ddl.auto");
080             if (null != autoFlag) {
081                configuration.setProperty("hibernate.hbm2ddl.auto", autoFlag);
082             }
083             /*
084              * add classes
085              */
086             final Set<Class<?>> entityClasses = getEntityClasses();
087             if (null != entityClasses) {
088                for (final Class<?> clazz : entityClasses) {
089                   configuration.addAnnotatedClass(clazz);
090                }
091             }
092             /*
093              * go for it
094              */
095             serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
096             return configuration.buildSessionFactory(serviceRegistry);
097          } catch (final Exception e) {
098             throw new ExceptionInInitializerError(e);
099          }
100       }
101    
102       /**
103        * the annotation scanner will have run; we can just query for annotated classes
104        */
105       protected static Set<Class<?>> getEntityClasses() throws PragmatachException {
106          try {
107             return AnnotationScanner.getAllClasses(Entity.class);
108          } catch (final Exception e) {
109             throw new PragmatachException("Exception in getAnnotatedClasses", e);
110          }
111       }
112    
113       public HibernateDAO(Class<T> typeClazz, Class<I> identifierClazz) {
114          this.typeClazz = typeClazz;
115          this.identifierClazz = identifierClazz;
116       }
117    
118       @Override
119       public long count() throws PragmatachException {
120          return (Long) this.find().setProjection(Projections.rowCount()).uniqueResult();
121       }
122    
123       /**
124        * delete
125        */
126       public void delete(T t) throws PragmatachException {
127          Session session = null;
128          Transaction transaction = null;
129          try {
130             session = getSessionFactory().openSession();
131             transaction = session.beginTransaction();
132             session.delete(t);
133             transaction.commit();
134          } catch (final Exception e) {
135             if (null != transaction) {
136                transaction.rollback();
137             }
138             throw new PragmatachException("Exception in delete", e);
139          } finally {
140             if (null != session) {
141                session.close();
142             }
143          }
144       }
145    
146       /**
147        * delete
148        */
149       @SuppressWarnings("unchecked")
150       public void deletebyId(I i) throws PragmatachException {
151          Session session = null;
152          Transaction transaction = null;
153          try {
154             session = getSessionFactory().openSession();
155             transaction = session.beginTransaction();
156             final T t = (T) session.get(typeClazz, i);
157             if (null != t) {
158                session.delete(t);
159             }
160             transaction.commit();
161          } catch (final Exception e) {
162             if (null != transaction) {
163                transaction.rollback();
164             }
165             throw new PragmatachException("Exception in deletebyId", e);
166          } finally {
167             if (null != session) {
168                session.close();
169             }
170          }
171       }
172    
173       /**
174        * find by fluent query. note that this leaves a session open!
175        */
176       public Criteria find() throws PragmatachException {
177          Session session = null;
178          try {
179             session = getSessionFactory().openSession();
180             return session.createCriteria(this.typeClazz);
181          } catch (final Exception e) {
182             throw new PragmatachException("Exception in find", e);
183          }
184       }
185    
186       /**
187        * find by id
188        */
189       @SuppressWarnings("unchecked")
190       public T findById(I i) throws PragmatachException {
191          Session session = null;
192          try {
193             session = getSessionFactory().openSession();
194             return (T) session.get(typeClazz, i);
195          } catch (final Exception e) {
196             throw new PragmatachException("Exception in findById", e);
197          } finally {
198             if (null != session) {
199                session.close();
200             }
201          }
202       }
203    
204       /**
205        * findall
206        */
207       @SuppressWarnings("unchecked")
208       public List<T> getAll() throws PragmatachException {
209          Session session = null;
210          try {
211             session = getSessionFactory().openSession();
212             final Criteria criteria = session.createCriteria(this.typeClazz);
213             return criteria.list();
214          } catch (final Exception e) {
215             throw new PragmatachException("Exception in findAll", e);
216          } finally {
217             if (null != session) {
218                session.close();
219             }
220          }
221       }
222    
223       @SuppressWarnings("unchecked")
224       @Override
225       public List<T> getAll(int start, int count) throws PragmatachException {
226          Session session = null;
227          try {
228             session = getSessionFactory().openSession();
229             final Criteria criteria = session.createCriteria(this.typeClazz);
230             criteria.setFirstResult(start);
231             criteria.setMaxResults(count);
232             return criteria.list();
233          } catch (final Exception e) {
234             throw new PragmatachException("Exception in findAll", e);
235          } finally {
236             if (null != session) {
237                session.close();
238             }
239          }
240       }
241    
242       public Class<I> getIdentifierClazz() {
243          return identifierClazz;
244       }
245    
246       public Class<T> getTypeClazz() {
247          return typeClazz;
248       }
249    
250       public void reloadConfig() {
251          sessionFactory = buildSessionFactory();
252       }
253    
254       /**
255        * save object
256        */
257       public void save(T t) throws PragmatachException {
258          Session session = null;
259          Transaction transaction = null;
260          try {
261             session = getSessionFactory().openSession();
262             transaction = session.beginTransaction();
263             session.save(t);
264             transaction.commit();
265          } catch (final Exception e) {
266             if (null != transaction) {
267                transaction.rollback();
268             }
269             throw new PragmatachException("Exception in save", e);
270          } finally {
271             if (null != session) {
272                session.close();
273             }
274          }
275       }
276    
277       /**
278        * update object
279        */
280       public void update(T t) throws PragmatachException {
281          Session session = null;
282          Transaction transaction = null;
283          try {
284             session = getSessionFactory().openSession();
285             transaction = session.beginTransaction();
286             session.update(t);
287             transaction.commit();
288          } catch (final Exception e) {
289             if (null != transaction) {
290                transaction.rollback();
291             }
292             throw new PragmatachException("Exception in update", e);
293          } finally {
294             if (null != session) {
295                session.close();
296             }
297          }
298       }
299    }