View Javadoc
1   /*******************************************************************************
2    *   Gisgraphy Project 
3    * 
4    *   This library is free software; you can redistribute it and/or
5    *   modify it under the terms of the GNU Lesser General Public
6    *   License as published by the Free Software Foundation; either
7    *   version 2.1 of the License, or (at your option) any later version.
8    * 
9    *   This library is distributed in the hope that it will be useful,
10   *   but WITHOUT ANY WARRANTY; without even the implied warranty of
11   *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12   *   Lesser General Public License for more details.
13   * 
14   *   You should have received a copy of the GNU Lesser General Public
15   *   License along with this library; if not, write to the Free Software
16   *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA
17   * 
18   *  Copyright 2008  Gisgraphy project 
19   *  David Masclet <davidmasclet@gisgraphy.com>
20   *  
21   *  
22   *******************************************************************************/
23  /**
24   *
25   */
26  package com.gisgraphy.domain.repository;
27  
28  import java.io.Serializable;
29  import java.util.ArrayList;
30  import java.util.List;
31  
32  import javax.persistence.PersistenceException;
33  
34  import org.hibernate.FlushMode;
35  import org.hibernate.HibernateException;
36  import org.hibernate.ObjectNotFoundException;
37  import org.hibernate.Query;
38  import org.hibernate.Session;
39  import org.slf4j.Logger;
40  import org.slf4j.LoggerFactory;
41  import org.springframework.dao.DataAccessResourceFailureException;
42  import org.springframework.orm.hibernate3.HibernateCallback;
43  import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
44  import org.springframework.util.Assert;
45  
46  /**
47   * A generic dao That implements basic functions with java 5.0 generics
48   * 
49   * @author <a href="mailto:david.masclet@gisgraphy.com">David Masclet</a>
50   */
51  public class GenericDao<T, PK extends Serializable> extends HibernateDaoSupport
52  	implements IDao<T, PK> {
53  
54      private Logger log = LoggerFactory.getLogger(this.getClass());
55  
56      protected Class<T> persistentClass;
57  
58      /*
59       * (non-Javadoc)
60       * 
61       * @see com.gisgraphy.domain.repository.IDao#getPersistenceClass()
62       */
63      public Class<T> getPersistenceClass() {
64  	return persistentClass;
65      }
66  
67      /**
68       * constructor
69       * 
70       * @param persistentClass
71       *                The specified Class for the GenericDao
72       */
73      public GenericDao(final Class<T> persistentClass) {
74  	this.persistentClass = persistentClass;
75      }
76  
77      /*
78       * (non-Javadoc)
79       * 
80       * @see com.gisgraphy.domain.repository.Idao#flushAndClear()
81       */
82      public void flushAndClear() {
83  	this.getHibernateTemplate().execute(new HibernateCallback() {
84  	    public Object doInHibernate(Session session)
85  		    throws PersistenceException {
86  		session.flush();
87  		session.clear();
88  		return null;
89  	    }
90  	});
91  
92      }
93  
94      /*
95       * (non-Javadoc)
96       * 
97       * @see com.gisgraphy.domain.repository.Idao#remove(java.io.Serializable)
98       */
99      public void remove(final T o) {
100 	Assert.notNull(o, "Can not remove a null object");
101 	this.getHibernateTemplate().delete(o);
102     }
103 
104     /*
105      * (non-Javadoc)
106      * 
107      * @see com.gisgraphy.domain.repository.Idao#save(java.lang.Object)
108      */
109     @SuppressWarnings("unchecked")
110     public T save(final T o) {
111 	Assert.notNull(o);
112 	this.getHibernateTemplate().saveOrUpdate(o);
113 	return o;
114 
115     }
116 
117     /*
118      * (non-Javadoc)
119      * 
120      * @see com.gisgraphy.domain.repository.IDao#setFlushMode(org.hibernate.FlushMode)
121      */
122     public void setFlushMode(final FlushMode flushMode) {
123 	Assert.notNull(flushMode);
124 	this.getHibernateTemplate().execute(new HibernateCallback() {
125 	    public Object doInHibernate(Session session) {
126 		session.setFlushMode(flushMode);
127 		return null;
128 	    }
129 	});
130 
131     }
132 
133     /*
134      * (non-Javadoc)
135      * 
136      * @see com.gisgraphy.domain.repository.IDao#get(java.io.Serializable)
137      */
138        public T get(final PK id) {
139 	Assert.notNull(id, "Can not retrieve an Ogject with a null id");
140 	T returnValue = null;
141 	try {
142 	    returnValue = (T) this.getHibernateTemplate().get(persistentClass, id);
143 	} catch (Exception e) {
144 	    log.info("could not retrieve object of type "
145 		    + persistentClass.getSimpleName() + " with id " + id, e);
146 	}
147 	return returnValue;
148     }
149 
150     /*
151      * (non-Javadoc)
152      * 
153      * @see com.gisgraphy.domain.repository.IDao#exists(java.io.Serializable)
154      */
155     public boolean exists(PK id) {
156 	return get(id) != null;
157     }
158 
159     /*
160      * (non-Javadoc)
161      * 
162      * @see com.gisgraphy.domain.repository.Idao#findAll()
163      */
164     @SuppressWarnings("unchecked")
165     public List<T> getAll() {
166 	List<T> returnValue = new ArrayList<T>();
167 	try {
168 	    return (List<T>) this.getHibernateTemplate().execute(
169 		    new HibernateCallback() {
170 
171 			public Object doInHibernate(Session session)
172 				throws PersistenceException {
173 			    String queryString = "from "
174 				    + persistentClass.getSimpleName();
175 
176 			    Query qry = session.createQuery(queryString);
177 			    qry.setCacheable(true);
178 			    List<T> results = (List<T>) qry.list();
179 			    if (results == null) {
180 				results = new ArrayList<T>();
181 			    }
182 			    return results;
183 			}
184 		    });
185 	} catch (DataAccessResourceFailureException e) {
186 	    log.info("could not retrieve all object of type "
187 		    + persistentClass.getName(), e);
188 	} catch (ObjectNotFoundException e) {
189 	    log.info("could not retrieve object of type "
190 		    + persistentClass.getName() + " with id ", e);
191 	} catch (HibernateException e) {
192 	    log.info("could not retrieve all object of type "
193 		    + persistentClass.getName(), e);
194 	} catch (IllegalStateException e) {
195 	    log.info("could not retrieve all object of type "
196 		    + persistentClass.getName(), e);
197 	}
198 	return returnValue;
199 
200     }
201 
202     /*
203      * (non-Javadoc)
204      * 
205      * @see com.gisgraphy.domain.repository.IDao#deleteAll(java.util.List)
206      */
207     public void deleteAll(List<T> list) {
208 	Assert.notNull(list);
209 	getHibernateTemplate().deleteAll(list);
210     }
211 
212     /*
213      * (non-Javadoc)
214      * 
215      * @see com.gisgraphy.domain.repository.IDao#count()
216      */
217     public long count() {
218 	return ((Long) this.getHibernateTemplate().execute(
219 		new HibernateCallback() {
220 
221 		    public Object doInHibernate(Session session)
222 			    throws PersistenceException {
223 			String queryString = "select count(*) from "
224 				+ persistentClass.getSimpleName();
225 
226 			Query qry = session.createQuery(queryString);
227 			qry.setCacheable(true);
228 			Long result = (Long) qry.uniqueResult();
229 			return result;
230 		    }
231 		})).longValue();
232     }
233 
234     /*
235      * (non-Javadoc)
236      * 
237      * @see com.gisgraphy.domain.repository.IDao#getAllPaginate(int, int)
238      */
239     @SuppressWarnings("unchecked")
240     public List<T> getAllPaginate(final int from, final int maxResults) {
241 	return (List<T>) this.getHibernateTemplate().execute(
242 		new HibernateCallback() {
243 
244 		    public Object doInHibernate(Session session)
245 			    throws PersistenceException {
246 			String queryString = "from "
247 				+ persistentClass.getSimpleName();
248 
249 			Query qry = session.createQuery(queryString);
250 			qry.setCacheable(true);
251 			if (maxResults > 0) {
252 			    qry.setMaxResults(maxResults);
253 			}
254 			if (from >= 1) {
255 			    qry.setFirstResult(from - 1);
256 			}
257 			List<T> results = (List<T>) qry.list();
258 			if (results == null) {
259 			    results = new ArrayList<T>();
260 			}
261 			return results;
262 		    }
263 		});
264 
265     }
266 
267     /*
268      * (non-Javadoc)
269      * 
270      * @see com.gisgraphy.domain.repository.IDao#deleteAll()
271      */
272     public int deleteAll() {
273 	int deleted = ((Integer) this.getHibernateTemplate().execute(
274 		new HibernateCallback() {
275 
276 		    public Object doInHibernate(Session session)
277 			    throws PersistenceException {
278 			//TODO zipcodes and alternatename are not deleted in cascade
279 			String queryString = "DELETE "
280 				+ persistentClass.getSimpleName();
281 			
282 			Query qry = session.createQuery(queryString);
283 			Integer deleted = Integer.valueOf(qry.executeUpdate());
284 			return deleted;
285 		    }
286 		})).intValue();
287 	return deleted;
288 
289     }
290 
291 }