View Javadoc

1   package com.melloware.jukes.db;
2   
3   import java.util.Collection;
4   import java.util.Iterator;
5   import java.util.List;
6   
7   import org.apache.commons.logging.Log;
8   import org.apache.commons.logging.LogFactory;
9   import org.hibernate.Criteria;
10  import org.hibernate.LockOptions;
11  import org.hibernate.Query;
12  import org.hibernate.criterion.Example;
13  import org.hibernate.criterion.Order;
14  
15  import com.melloware.jukes.db.orm.AbstractJukesObject;
16  import com.melloware.jukes.exception.InfrastructureException;
17  
18  /**
19   * Static methods for access data using Hibernate.
20   * <p>
21   * Copyright (c) 1999-2007 Melloware, Inc. <http://www.melloware.com>
22   * @author Emil A. Lefkof III <info@melloware.com>
23   * @version 4.0 AZ 2009
24   */
25  public final class HibernateDao {
26     private static final Log LOG = LogFactory.getLog(HibernateDao.class);
27  
28     /**
29      * Private No Instantiation.
30      */
31     private HibernateDao() {
32        super();
33     }
34  
35     /**
36      * Attaches a clean instance of an object to a session.
37      * <p>
38      * @param instance the instance to attach
39      */
40     public static void attachClean(final AbstractJukesObject instance) {
41        LOG.debug("attaching clean instance");
42        try {
43           HibernateUtil.getSession().buildLockRequest(LockOptions.NONE).lock(instance);
44           LOG.debug("attach successful");
45        } catch (RuntimeException re) {
46           LOG.error(re.getMessage(), re);
47           throw new InfrastructureException(re);
48        }
49     }
50  
51     /**
52      * Attaches a dirty instance of an object to a session.
53      * <p>
54      * @param instance the instance to attach
55      */
56     public static void attachDirty(final AbstractJukesObject instance) {
57        LOG.debug("attaching dirty instance");
58        try {
59           HibernateUtil.getSession().saveOrUpdate(instance);
60           LOG.debug("attach successful");
61        } catch (RuntimeException re) {
62           LOG.error(re.getMessage(), re);
63           throw new InfrastructureException(re);
64        }
65     }
66  
67     /**
68      * Gets a count using a HQL Query.
69      * <p>
70      * @param aHQLQuery the query to run
71      * @return the count
72      */
73     public static long count(final String aHQLQuery) {
74        LOG.debug("Count : " + aHQLQuery);
75        try {
76           // final int count = ((Integer)
77           // HibernateUtil.getSession().createQuery("select count (*) from " +
78           // aHQLQuery)
79           // .uniqueResult()).intValue();
80           // AZ change type from int to long
81           final long count = ((Long) HibernateUtil.getSession().createQuery("select count (*) from " + aHQLQuery)
82                    .uniqueResult()).longValue();
83           return count;
84        } catch (RuntimeException re) {
85           LOG.error(re.getMessage(), re);
86           throw new InfrastructureException(re);
87        }
88     }
89  
90     /**
91      * Gets a sum of a long type column
92      * <p>
93      * @param aClass the class to sum up
94      * @param aLongField the field to sum up
95      * @return the sum
96      */
97     public static long sum(final Class aClass, final String aLongField) {
98        LOG.debug("Sum : " + aClass.getName());
99        try {
100          final long sum = ((Long) HibernateUtil.getSession().createQuery(
101                   "select sum(" + aLongField + ") from " + aClass.getName()).uniqueResult()).longValue();
102          return sum;
103       } catch (RuntimeException re) {
104          LOG.error(re.getMessage(), re);
105          throw new InfrastructureException(re);
106       }
107    }
108 
109    /**
110     * Counts ALL of a certain domain class.
111     * <p>
112     * @param aClass the class to count
113     * @return the count
114     */
115    public static long countAll(final Class aClass) {
116       LOG.debug("Count All " + aClass.getName());
117       try {
118          final long count = ((Long) HibernateUtil.getSession().createQuery("select count(id) from " + aClass.getName())
119                   .uniqueResult()).longValue();
120          return count;
121       } catch (RuntimeException re) {
122          LOG.error(re.getMessage(), re);
123          throw new InfrastructureException(re);
124       }
125    }
126 
127    /**
128     * Creates a criteria for the Class.
129     * <p>
130     * @param aClass the class to create a criteria for.
131     * @return the Criteria object
132     */
133    public static Criteria createCriteria(final Class aClass) {
134       return HibernateUtil.getSession().createCriteria(aClass).setCacheable(false);
135    }
136 
137    /**
138     * Delete a persistent object from the store.
139     * <p>
140     * @param persistentInstance the object to delete
141     */
142    public static void delete(final AbstractJukesObject persistentInstance) {
143       LOG.debug("deleting instance");
144       try {
145          HibernateUtil.getSession().delete(persistentInstance);
146          LOG.debug("delete successful");
147       } catch (RuntimeException re) {
148          LOG.error(re.getMessage(), re);
149          throw new InfrastructureException(re);
150       }
151    }
152 
153    /**
154     * Deletes a whole collection from the store.
155     * <p>
156     * @param aCollection the collection to delete
157     */
158    public static void deleteAll(final Collection aCollection) {
159       LOG.debug("deleting collection");
160       if (aCollection == null) {
161          return;
162       }
163       try {
164          final Iterator iterator = aCollection.iterator();
165          while (iterator.hasNext()) {
166             final AbstractJukesObject element = (AbstractJukesObject) iterator.next();
167             iterator.remove();
168             HibernateDao.delete(element);
169          }
170 
171          HibernateUtil.getSession().flush();
172          LOG.debug("deleting collection successful");
173       } catch (RuntimeException re) {
174          LOG.error(re.getMessage(), re);
175          throw new InfrastructureException(re);
176       }
177    }
178 
179    /**
180     * Find all of an object with a specified sort order.
181     * <p>
182     * @param aClass the class to find
183     * @param aSortColumn the sort column to use
184     * @return a List of all objects found
185     */
186    public static List findAll(final Class aClass, final String aSortColumn) {
187       if (LOG.isDebugEnabled()) {
188          LOG.debug("geting ALL " + aClass.getName());
189       }
190 
191       List items;
192       try {
193          final Criteria criteria = createCriteria(aClass);
194          criteria.addOrder(Order.asc(aSortColumn));
195          items = criteria.list();
196       } catch (RuntimeException re) {
197          LOG.error(re.getMessage(), re);
198          throw new InfrastructureException(re);
199       }
200       return items;
201    }
202 
203    /**
204     * Finds persistent objects from the store by Criteria provided.
205     * <p>
206     * @param criteria the criteria object to use
207     * @return a List of all objects found
208     */
209    public static List findByCriteria(final Criteria criteria) {
210       LOG.debug("finding instance by criteria");
211       try {
212          final List results = criteria.list();
213          LOG.debug("find by criteria successful, result size: " + results.size());
214          return results;
215       } catch (RuntimeException re) {
216          LOG.error(re.getMessage(), re);
217          throw new InfrastructureException(re);
218       }
219    }
220 
221    /**
222     * Finds persistent objects from the store by Example provided.
223     * <p>
224     * @param instance the persistent object to use an as example
225     * @return a List of all objects found
226     */
227    public static List findByExample(final AbstractJukesObject instance) {
228       LOG.debug("finding instance by example");
229       try {
230          final Example example = Example.create(instance);
231          final List results = HibernateUtil.getSession().createCriteria(instance.getClass()).add(example).list();
232          LOG.debug("find by example successful, result size: " + results.size());
233          return results;
234       } catch (RuntimeException re) {
235          LOG.error(re.getMessage(), re);
236          throw new InfrastructureException(re);
237       }
238    }
239 
240    /**
241     * Find by primary key.
242     * <p>
243     * @param aClass the Class to look for
244     * @param id the primary key
245     * @return a persisten object if found by primary key
246     */
247    public static AbstractJukesObject findById(final Class aClass, final long id) {
248       return findById(aClass, Long.valueOf(id));
249    }
250 
251    /**
252     * Find by primary key.
253     * <p>
254     * @param aClass the Class to look for
255     * @param id the primary key
256     * @return a persisten object if found by primary key
257     */
258    public static AbstractJukesObject findById(final Class aClass, final Long id) {
259       LOG.debug("getting instance with id: " + id);
260       try {
261          final AbstractJukesObject instance = (AbstractJukesObject) HibernateUtil.getSession().get(aClass, id);
262          if (instance == null) {
263             LOG.debug("get successful, no instance found");
264          } else {
265             LOG.debug("get successful, instance found");
266          }
267          return instance;
268       } catch (RuntimeException re) {
269          LOG.error(re.getMessage(), re);
270          throw new InfrastructureException(re);
271       }
272    }
273 
274    /**
275     * Find all of an object with a specified HQL Query.
276     * <p>
277     * @param aHQLQuery the query to execute
278     * @return a List of all objects found
279     */
280    public static List findByQuery(final String aHQLQuery) {
281       if (LOG.isDebugEnabled()) {
282          LOG.debug("findByQuery " + aHQLQuery);
283       }
284 
285       List items;
286       try {
287          items = HibernateUtil.getSession().createQuery(aHQLQuery).list();
288       } catch (RuntimeException re) {
289          LOG.error(re.getMessage(), re);
290          throw new InfrastructureException(re);
291       }
292       return items;
293    }
294 
295    /**
296     * Find all of an object with a specified HQL Query.
297     * <p>
298     * @param aHQLQuery the query to execute
299     * @param aMaxResults the maximum results to return
300     * @return a List of all objects found
301     */
302    public static List findByQuery(final String aHQLQuery, final int aMaxResults) {
303       if (LOG.isDebugEnabled()) {
304          LOG.debug("findByQuery " + aHQLQuery);
305       }
306 
307       List items;
308       try {
309          final Query query = HibernateUtil.getSession().createQuery(aHQLQuery);
310          query.setMaxResults(aMaxResults);
311          items = query.list();
312       } catch (RuntimeException re) {
313          LOG.error(re.getMessage(), re);
314          throw new InfrastructureException(re);
315       }
316       return items;
317    }
318 
319    /**
320     * Finds a single object using the aHQLQuery.
321     * <p>
322     * @param aHQLQuery the query to execute
323     * @return a List of all objects found
324     */
325    public static AbstractJukesObject findUniqueByQuery(final String aHQLQuery) {
326       if (LOG.isDebugEnabled()) {
327          LOG.debug("findUniqueByQuery " + aHQLQuery);
328       }
329 
330       AbstractJukesObject result = null;
331       try {
332          result = (AbstractJukesObject) HibernateUtil.getSession().createQuery(aHQLQuery).uniqueResult();
333       } catch (RuntimeException re) {
334          LOG.error(re.getMessage(), re);
335          throw new InfrastructureException(re);
336       }
337       return result;
338    }
339 
340    /**
341     * Finds a single persistent object from the store by Example provided.
342     * <p>
343     * @param instance the persistent object to use an as example
344     * @return the object found if one
345     */
346    public static AbstractJukesObject findUniqueByExample(final AbstractJukesObject instance) {
347       LOG.debug("finding unique instance by example");
348       AbstractJukesObject result = null;
349       try {
350          final Example example = Example.create(instance);
351          result = (AbstractJukesObject) HibernateUtil.getSession().createCriteria(instance.getClass()).add(example)
352                   .uniqueResult();
353          LOG.debug("find by unique example successful ");
354       } catch (RuntimeException re) {
355          LOG.error(re.getMessage(), re);
356          throw new InfrastructureException(re);
357       }
358       return result;
359    }
360 
361    /**
362     * Merges an instance of a persistable object into a session and returns the
363     * merged object.
364     * <p>
365     * @param detachedInstance the instance to attach
366     */
367    public static AbstractJukesObject merge(final AbstractJukesObject detachedInstance) {
368       LOG.debug("merging Album instance");
369       try {
370          final AbstractJukesObject result = (AbstractJukesObject) HibernateUtil.getSession().merge(detachedInstance);
371          LOG.debug("merge successful");
372          return result;
373       } catch (RuntimeException re) {
374          LOG.error(re.getMessage(), re);
375          throw new InfrastructureException(re);
376       }
377    }
378 
379    /**
380     * Persist an object to the store.
381     * <p>
382     * @param transientInstance the object to persist
383     */
384    public static void persist(final AbstractJukesObject transientInstance) {
385       LOG.debug("persisting instance");
386       try {
387          HibernateUtil.getSession().persist(transientInstance);
388          LOG.debug("persist successful");
389       } catch (RuntimeException re) {
390          LOG.error(re.getMessage(), re);
391          throw new InfrastructureException(re);
392       }
393    }
394 
395    /**
396     * Persist an object to the store.
397     * <p>
398     * @param transientInstance the object to persist
399     */
400    public static void saveOrUpdate(final AbstractJukesObject transientInstance) {
401       LOG.debug("saveOrUpdate instance");
402       try {
403          HibernateUtil.getSession().saveOrUpdate(transientInstance);
404          LOG.debug("saveOrUpdate successful");
405       } catch (RuntimeException re) {
406          LOG.error(re.getMessage(), re);
407          throw new InfrastructureException(re);
408       }
409    }
410 
411    /**
412     * Refreshes an object from the database. If you think data may be stale and
413     * need updating.
414     * <p>
415     * @param transientInstance the object to refresh
416     */
417    public static void refresh(final AbstractJukesObject transientInstance) {
418       LOG.debug("refreshing instance");
419       try {
420          HibernateUtil.getSession().refresh(transientInstance);
421          LOG.debug("refreshing successful");
422       } catch (RuntimeException re) {
423          LOG.error(re.getMessage(), re);
424          throw new InfrastructureException(re);
425       }
426    }
427 
428    public static void refreshAll(final Collection aCollection) {
429       LOG.debug("refreshing collection");
430       if (aCollection == null) {
431          return;
432       }
433       try {
434          final Iterator iterator = aCollection.iterator();
435          while (iterator.hasNext()) {
436             final AbstractJukesObject element = (AbstractJukesObject) iterator.next();
437             HibernateDao.refresh(element);
438          }
439          LOG.debug("refreshing collection successful");
440       } catch (RuntimeException re) {
441          LOG.error(re.getMessage(), re);
442          throw new InfrastructureException(re);
443       }
444    }
445 
446 }