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