View Javadoc

1   package com.germinus.merlin.dao;
2   
3   import java.io.Serializable;
4   import java.util.List;
5   
6   import org.apache.commons.logging.Log;
7   import org.apache.commons.logging.LogFactory;
8   import org.springframework.orm.ObjectRetrievalFailureException;
9   import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
10  
11  /**
12   * This class serves as the Base class for all other DAOs - namely to hold
13   * common CRUD methods that they might all use. You should only need to extend
14   * this class when your require custom CRUD logic.
15   * <p/>
16   * <p>To register this class in your Spring context file, use the following XML.
17   * <pre>
18   *      &lt;bean id="fooDao" class="org.appfuse.dao.hibernate.GenericDaoHibernate"&gt;
19   *          &lt;constructor-arg value="org.appfuse.model.Foo"/&gt;
20   *          &lt;property name="sessionFactory" ref="sessionFactory"/&gt;
21   *      &lt;/bean&gt;
22   * </pre>
23   *
24   * @author <a href="mailto:bwnoll@gmail.com">Bryan Noll</a>
25   */
26  public abstract class GenericDaoHibernate<T, PK extends Serializable> 
27  	extends HibernateDaoSupport implements IGenericDao<T, PK>  {
28     
29  	protected final Log log = LogFactory.getLog(getClass());
30      private Class<T> persistentClass;
31  
32      public GenericDaoHibernate(Class<T> persistentClass) {
33          this.persistentClass = persistentClass;
34      }
35  
36      @SuppressWarnings("unchecked")
37      public List<T> getAll() {
38          return super.getHibernateTemplate().loadAll(this.persistentClass);
39      }
40  
41      @SuppressWarnings("unchecked")
42      public T get(PK id) {
43          T entity = (T) super.getHibernateTemplate().get(this.persistentClass, id);
44  
45          if (entity == null) {
46              log.warn("Uh oh, '" + this.persistentClass + "' object with id '" + id + "' not found...");
47              throw new ObjectRetrievalFailureException(this.persistentClass, id);
48          }
49  
50          return entity;
51      }
52  
53      @SuppressWarnings("unchecked")
54      public boolean exists(PK id) {
55          T entity = (T) super.getHibernateTemplate().get(this.persistentClass, id);
56          if (entity == null) {
57              return false;
58          } else {
59              return true;
60          }
61      }
62  
63      @SuppressWarnings("unchecked")
64      public T save(T object) {
65          return (T) super.getHibernateTemplate().merge(object);
66      }
67  
68      public void remove(PK id) {
69          super.getHibernateTemplate().delete(this.get(id));
70      }
71      
72  }