码迷,mamicode.com
首页 > 编程语言 > 详细

baseDao 使用spring3+hibernate4方式

时间:2016-04-11 11:38:50      阅读:272      评论:0      收藏:0      [点我收藏+]

标签:

启动异常:

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) this.getHibernateTemplate().load(this.getClass(), id);
171         return (T) getSession().load(this.getClass(), id);
172     }
173 
174     @SuppressWarnings("unchecked")
175     public T getByHql(String hql, Object[] params) {
176         Query query = this.getSession().createQuery(hql);
177         for (int i = 0; i < params.length; i++) {
178             query.setParameter(i, params[i]);
179         }
180         return (T) query.uniqueResult();
181     }
182 
183     @SuppressWarnings("unchecked")
184     public List<T> getByHqlNotIn(String hql, Object[] params) {
185         System.out.println("Tclass:" + Tclass);
186         Query query = this.getSession().createSQLQuery(hql).addEntity(Tclass);
187         List<T> list = null;
188         for (int i = 0; i < params.length; i++) {
189             query.setParameter(i, params[i]);
190         }
191         list = query.list();
192         return list;
193     }
194 
195     @SuppressWarnings("unchecked")
196     public List<T> listFenYeAddparams(int firstResult, int maxResults,
197             String hql, Object[] params) {
198         Query query = this.getSession().createQuery(hql);
199         List<T> list = null;
200         if (null == params || params.length == 0) {
201             list = query.setMaxResults(maxResults).setFirstResult(firstResult)
202                     .list();
203         }
204         if (null != params || params.length != 0) {
205             for (int i = 0; i < params.length; i++) {
206                 query.setParameter(i, params[i]);
207             }
208             list = query.setMaxResults(maxResults).setFirstResult(firstResult).list();
209         }
210         return list;
211     }
212 
213     @SuppressWarnings("unchecked")
214     public List<T> listFenYeNotIn(int firstResult, int maxResults, String hql,
215             Object[] params) {
216         Query query = this.getSession().createSQLQuery(hql).addEntity(Tclass);
217         List<T> list = null;
218         if (null == params || params.length == 0) {
219             list = query.setMaxResults(maxResults).setFirstResult(firstResult).list();
220         }
221         if (null != params || params.length != 0) {
222             for (int i = 0; i < params.length; i++) {
223                 System.out.println("params:" + params[i]);
224                 query.setParameter(i, params[i]);
225             }
226             list = query.setMaxResults(maxResults).setFirstResult(firstResult).list();
227         }
228         return list;
229     }
230 
231     @SuppressWarnings("unchecked")
232     public List<T> listNotIn(String hql, Object[] params) {
233         Query query = this.getSession().createSQLQuery(hql).addEntity(Tclass);
234         List<T> list = null;
235         if (null != params || params.length != 0) {
236             for (int i = 0; i < params.length; i++) {
237                 System.out.println("params:" + params[i]);
238                 query.setParameter(i, params[i]);
239             }
240         }
241         list = query.list();
242         return list;
243     }
244 
245     public long getCount(String hql, Object[] params) {
246         Query query = this.getSession().createQuery(hql);
247         if (null != params || params.length != 0) {
248             for (int i = 0; i < params.length; i++) {
249                 query.setParameter(i, params[i]);
250             }
251         }
252         return (Long) query.uniqueResult();
253     }
254 
255     @SuppressWarnings("unchecked")
256     public List<T> queryPage(Map map, int firstResult, int maxResults,
257             String hql) {
258         StringBuffer buffer = new StringBuffer(hql);
259         StringBuffer wherestring = new StringBuffer();
260         Iterator paramnames = map.keySet().iterator();
261         while (paramnames.hasNext()) {
262             String paramname = (String) paramnames.next();
263             String value = null;
264             value = String.valueOf(map.get(paramname));
265             if (value != null) {
266                 value = value.trim();
267                 if (value.equals("")) {
268                     continue;
269                 }
270             }
271             if (wherestring.length() == 0) {
272                 wherestring.append(" where ");
273             } else {
274                 wherestring.append(" and ");
275             }
276             wherestring.append(paramname).append("=").append(value);
277             buffer.append(wherestring);
278         }
279         Query query = this.getSession().createQuery(buffer.toString());
280         List<T> list = query.setMaxResults(maxResults).setFirstResult(firstResult).list();
281         return list;
282     }
283 
284     public long getCount(String hql, Map map) {
285         StringBuffer buffer = new StringBuffer(hql);
286         StringBuffer wherestring = new StringBuffer();
287         Iterator paramnames = map.keySet().iterator();
288         while (paramnames.hasNext()) {
289             String paramname = (String) paramnames.next();
290             String value = null;
291             value = String.valueOf(map.get(paramname));
292             if (value != null) {
293                 value = value.trim();
294                 if (value.equals("")) {
295                     continue;
296                 }
297             }
298             if (wherestring.length() == 0) {
299                 wherestring.append(" where ");
300             } else {
301                 wherestring.append(" and ");
302             }
303             wherestring.append(paramname).append("=").append(value);
304             buffer.append(wherestring);
305         }
306         Query query = this.getSession().createQuery(buffer.toString());
307         return (Long) query.uniqueResult();
308     }
309 
310     public int update(String hql, Object[] params) {
311         Query query = this.getSession().createQuery(hql);
312         if (params == null) {
313             return query.executeUpdate();
314         }
315         for (int i = 0; i < params.length; i++) {
316             query.setParameter(i, params[i]);
317         }
318         return query.executeUpdate();
319     }
320 
321     public int save(String hql, Object[] params) {
322         Query query = this.getSession().createQuery(hql);
323         for (int i = 0; i < params.length; i++) {
324             query.setParameter(i, params[i]);
325         }
326         return query.executeUpdate();
327     }
328 
329     public T queryObject(String hql, Object[] params) {
330         Query query = this.getSession().createQuery(hql);
331         for (int i = 0; i < params.length; i++) {
332             query.setParameter(i, params[i]);
333         }
334         return (T) query.uniqueResult();
335     }
336 
337     @SuppressWarnings("rawtypes")
338     public Class getTclass() {
339         return Tclass;
340     }
341 
342     @SuppressWarnings("rawtypes")
343     public void setTclass(Class tclass) {
344         Tclass = tclass;
345     }
346 }
347     

 

 




baseDao 使用spring3+hibernate4方式

标签:

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!