baseDao 使用spring3+hibernate4方式

启动异常:

java.lang.ClassCastException: org.springframework.orm.hibernate4.SessionHolder cannot be cast to org.springframework.orm.hibernate3.SessionHolder

由于hibernate4已经完全可以实现事务了 与spring3.1中的hibernatedao,hibernateTemplete等有冲突,所以spring3.1里已经不提供hibernatedaosupport,hibernateTemplete了,只能用hibernate原始的方式用session。 获得session:getSessionFactory().getCurrentSession()。

 1 package org.konghao.basic.dao;
 2 
 3 import java.io.Serializable;
 4 import java.util.List;
 5 import java.util.Map;
 6 /**
 7  * 
 8  * @author zh
 9  *
10  * @param <T>
11  */
12 public interface IBaseDao<T extends Serializable> {
13     
14     void save(T t);
15     void update(T t);
16     int save(String hql,Object[] params);
17     void delete(T t);
18     void deleteById(String hql, Object[] params);
19     int update(String hql,Object[] params);
20     T get(final Serializable id);
21     T load(final Serializable id);
22     public List<T> listNotIn(String hql, Object[] params);
23     public List<T> getByHqlNotIn(String hql, Object[] params);
24     List<T> listAll();
25     List<T> listFenYe(int firstResult, int maxResults);
26     List<T> listFenYeNotIn(int firstResult, int maxResults, String hql, Object[] params);
27     long getCount();
28     long getCount(String hql,Object[] params);
29     List<T> listByHql(String hql,Object[] params);
30     T getByHql(String hql,Object[] params);
31     List<T> listFenYeAddparams(int firstResult, int maxResults,String hql,Object[] params);
32     List<T> queryPage(Map map,int firstResult, int maxResults,String hql) ;
33     long getCount(String hql, Map map);
34 }
35     

Hibernate4方式

  1 package org.konghao.basic.dao;
  2 
  3 import java.io.Serializable;
  4 import java.lang.reflect.ParameterizedType;
  5 import java.lang.reflect.Type;
  6 import java.util.Iterator;
  7 import java.util.List;
  8 import java.util.Map;
  9 
 10 import javax.inject.Inject;
 11 
 12 import org.hibernate.Query;
 13 import org.hibernate.Session;
 14 import org.hibernate.SessionFactory;
 15 
 16 /**
 17  * BaseDaoImpl不能在类型未确定前直接实例化
 18  * 
 19  * @author zh
 20  * @param <T>
 21  */
 22 public class BaseDao<T extends Serializable>  implements IBaseDao<T> {
 23 
 24     private SessionFactory sessionFactory;
 25     
 26     public SessionFactory getSessionFactory() {
 27         return sessionFactory;
 28     }
 29 
 30     @Inject
 31     public void setSessionFactory(SessionFactory sessionFactory) {
 32         this.sessionFactory = sessionFactory;
 33     }
 34 
 35     protected Session getSession() {
 36         return sessionFactory.getCurrentSession();
 37     }
 38 
 39 
 40     @SuppressWarnings("rawtypes")
 41     private Class Tclass;
 42 
 43     @SuppressWarnings("rawtypes")
 44     public BaseDao() {
 45         Type type = this.getClass().getGenericSuperclass();
 46         if (type.toString().indexOf("BaseDao") != -1) {
 47             ParameterizedType type1 = (ParameterizedType) type;
 48             Type[] types = type1.getActualTypeArguments();
 49             setTclass((Class) types[0]);
 50         } else {
 51             type = ((Class) type).getGenericSuperclass();
 52             ParameterizedType type1 = (ParameterizedType) type;
 53             Type[] types = type1.getActualTypeArguments();
 54             setTclass((Class) types[0]);
 55         }
 56     }
 57 
 58     /**
 59      * 保存对象
 60      * 
 61      * @param Object
 62      */
 63 
 64     public void save(T t) {
 65         // this.getHibernateTemplate().save(t)
 66         getSession().save(t);
 67 
 68     }
 69 
 70     /**
 71      * 更新对象内容
 72      * 
 73      * @param Object
 74      */
 75     public void update(T t) {
 76         // this.getHibernateTemplate().update(t);
 77         getSession().update(t);
 78     }
 79 
 80     /**
 81      * 删除对象
 82      * 
 83      * @param t
 84      */
 85     public void delete(T t) {
 86         // this.getHibernateTemplate().delete(t);
 87         getSession().delete(t);
 88     }
 89 
 90     public void deleteById(String hql, Object[] params) {
 91         Query query = this.getSession().createQuery(hql);
 92         for (int i = 0; i < params.length; i++) {
 93             query.setParameter(i, params[i]);
 94         }
 95         query.executeUpdate();
 96     }
 97 
 98     /**
 99      * ͨ通过ID 得到对象
100      * 
101      * @param Serializable
102      */
103     @SuppressWarnings("unchecked")
104     public T get(Serializable id) {
105         // return (T) this.getHibernateTemplate().get(getTclass(), id);
106         return (T) getSession().get(getTclass(), id);
107     }
108 
109     /**
110      * 取得所有对象
111      * 
112      */
113     @SuppressWarnings("unchecked")
114     public List<T> listAll() {
115         String hql = "from " + getTclass().getSimpleName();
116         return this.getSession().createQuery(hql).list();
117     }
118 
119     /**
120      * hql解决方案
121      * 
122      * @param String
123      *            hql
124      * 
125      * @param Object
126      *            [] params 参数列表 顺序不能颠倒
127      */
128 
129     @SuppressWarnings("unchecked")
130     public List<T> listByHql(String hql, Object[] params) {
131         Query query = this.getSession().createQuery(hql);
132         if (null == params || params.length == 0) {
133             return query.list();
134         } else {
135             for (int i = 0; i < params.length; i++) {
136                 query.setParameter(i, params[i]);
137             }
138         }
139         return query.list();
140     }
141 
142     /**
143      * 同类分页
144      * 
145      * @param int firstResult 从第几条开始
146      * @param int maxResults 要取几条
147      */
148     @SuppressWarnings({ "unchecked" })
149     public List<T> listFenYe(int firstResult, int maxResults) {
150         String hql = "from " + getTclass().getSimpleName();
151         Query query = this.getSession().createQuery(hql)
152                 .setMaxResults(maxResults).setFirstResult(firstResult);
153         return query.list();
154     }
155 
156     /**
157      * 取得行数
158      */
159 
160     public long getCount() {
161         String hql = "select count(*) from " + getTclass().getSimpleName();
162         return (Long) this.getSession().createQuery(hql).uniqueResult();
163     }
164 
165     /**
166      * 懒加载load
167      */
168     @SuppressWarnings("unchecked")
169     public T load(Serializable id) {
170         return (T) getSession().load(getTclass(), id);
171     }
172 
173     @SuppressWarnings("unchecked")
174     public T getByHql(String hql, Object[] params) {
175         Query query = this.getSession().createQuery(hql);
176         for (int i = 0; i < params.length; i++) {
177             query.setParameter(i, params[i]);
178         }
179         return (T) query.uniqueResult();
180     }
181 
182     @SuppressWarnings("unchecked")
183     public List<T> getByHqlNotIn(String hql, Object[] params) {
184         System.out.println("Tclass:" + Tclass);
185         Query query = this.getSession().createSQLQuery(hql).addEntity(Tclass);
186         List<T> list = null;
187         for (int i = 0; i < params.length; i++) {
188             query.setParameter(i, params[i]);
189         }
190         list = query.list();
191         return list;
192     }
193 
194     @SuppressWarnings("unchecked")
195     public List<T> listFenYeAddparams(int firstResult, int maxResults,
196             String hql, Object[] params) {
197         Query query = this.getSession().createQuery(hql);
198         List<T> list = null;
199         if (null == params || params.length == 0) {
200             list = query.setMaxResults(maxResults).setFirstResult(firstResult)
201                     .list();
202         }
203         if (null != params || params.length != 0) {
204             for (int i = 0; i < params.length; i++) {
205                 query.setParameter(i, params[i]);
206             }
207             list = query.setMaxResults(maxResults).setFirstResult(firstResult).list();
208         }
209         return list;
210     }
211 
212     @SuppressWarnings("unchecked")
213     public List<T> listFenYeNotIn(int firstResult, int maxResults, String hql,
214             Object[] params) {
215         Query query = this.getSession().createSQLQuery(hql).addEntity(Tclass);
216         List<T> list = null;
217         if (null == params || params.length == 0) {
218             list = query.setMaxResults(maxResults).setFirstResult(firstResult).list();
219         }
220         if (null != params || params.length != 0) {
221             for (int i = 0; i < params.length; i++) {
222                 System.out.println("params:" + params[i]);
223                 query.setParameter(i, params[i]);
224             }
225             list = query.setMaxResults(maxResults).setFirstResult(firstResult).list();
226         }
227         return list;
228     }
229 
230     @SuppressWarnings("unchecked")
231     public List<T> listNotIn(String hql, Object[] params) {
232         Query query = this.getSession().createSQLQuery(hql).addEntity(Tclass);
233         List<T> list = null;
234         if (null != params || params.length != 0) {
235             for (int i = 0; i < params.length; i++) {
236                 System.out.println("params:" + params[i]);
237                 query.setParameter(i, params[i]);
238             }
239         }
240         list = query.list();
241         return list;
242     }
243 
244     public long getCount(String hql, Object[] params) {
245         Query query = this.getSession().createQuery(hql);
246         if (null != params || params.length != 0) {
247             for (int i = 0; i < params.length; i++) {
248                 query.setParameter(i, params[i]);
249             }
250         }
251         return (Long) query.uniqueResult();
252     }
253 
254     @SuppressWarnings("unchecked")
255     public List<T> queryPage(Map map, int firstResult, int maxResults,
256             String hql) {
257         StringBuffer buffer = new StringBuffer(hql);
258         StringBuffer wherestring = new StringBuffer();
259         Iterator paramnames = map.keySet().iterator();
260         while (paramnames.hasNext()) {
261             String paramname = (String) paramnames.next();
262             String value = null;
263             value = String.valueOf(map.get(paramname));
264             if (value != null) {
265                 value = value.trim();
266                 if (value.equals("")) {
267                     continue;
268                 }
269             }
270             if (wherestring.length() == 0) {
271                 wherestring.append(" where ");
272             } else {
273                 wherestring.append(" and ");
274             }
275             wherestring.append(paramname).append("=").append(value);
276             buffer.append(wherestring);
277         }
278         Query query = this.getSession().createQuery(buffer.toString());
279         List<T> list = query.setMaxResults(maxResults).setFirstResult(firstResult).list();
280         return list;
281     }
282 
283     public long getCount(String hql, Map map) {
284         StringBuffer buffer = new StringBuffer(hql);
285         StringBuffer wherestring = new StringBuffer();
286         Iterator paramnames = map.keySet().iterator();
287         while (paramnames.hasNext()) {
288             String paramname = (String) paramnames.next();
289             String value = null;
290             value = String.valueOf(map.get(paramname));
291             if (value != null) {
292                 value = value.trim();
293                 if (value.equals("")) {
294                     continue;
295                 }
296             }
297             if (wherestring.length() == 0) {
298                 wherestring.append(" where ");
299             } else {
300                 wherestring.append(" and ");
301             }
302             wherestring.append(paramname).append("=").append(value);
303             buffer.append(wherestring);
304         }
305         Query query = this.getSession().createQuery(buffer.toString());
306         return (Long) query.uniqueResult();
307     }
308 
309     public int update(String hql, Object[] params) {
310         Query query = this.getSession().createQuery(hql);
311         if (params == null) {
312             return query.executeUpdate();
313         }
314         for (int i = 0; i < params.length; i++) {
315             query.setParameter(i, params[i]);
316         }
317         return query.executeUpdate();
318     }
319 
320     public int save(String hql, Object[] params) {
321         Query query = this.getSession().createQuery(hql);
322         for (int i = 0; i < params.length; i++) {
323             query.setParameter(i, params[i]);
324         }
325         return query.executeUpdate();
326     }
327 
328     public T queryObject(String hql, Object[] params) {
329         Query query = this.getSession().createQuery(hql);
330         for (int i = 0; i < params.length; i++) {
331             query.setParameter(i, params[i]);
332         }
333         return (T) query.uniqueResult();
334     }
335 
336     @SuppressWarnings("rawtypes")
337     public Class getTclass() {
338         if(Tclass == null){
339             Type type = this.getClass().getGenericSuperclass();
340             ParameterizedType type2 = (ParameterizedType) type;
341             Type[] types = type2.getActualTypeArguments();
342             Tclass = (Class<?>) types[0];
343         }
344         return Tclass;
345     }
346 
347     @SuppressWarnings("rawtypes")
348     public void setTclass(Class tclass) {
349         Tclass = tclass;
350     }
351 }
352     
 




原文地址:https://www.cnblogs.com/a757956132/p/5377426.html