hibernate常用增删改查接口实现

  1 /**
  2  * 作者:宫长明
  3  * 
  4  */
  5 
  6 
  7 import java.io.Serializable;
  8 import java.util.List;
  9 import java.util.Map;
 10 
 11 import org.hibernate.criterion.Criterion;
 12 import org.hibernate.criterion.DetachedCriteria;
 13 
 14 @SuppressWarnings("unchecked")
 15 public interface IBaseDao<T,PK extends Serializable> {
 16     /**
 17      * 保存PO对象
 18      * @param obj PO所要保存值对象
 19      * @return 保存记录数 0:为保存失败
 20      * */
 21     public void save(T obj);
 22     /**
 23      * 保存PO对象
 24      * @param obj PO所要保存值对象
 25      * @return 保存记录数 0:为保存失败
 26      * */
 27     public void saveByObj(T obj);
 28     
 29     /**
 30      * 保存多个PO对象,将PO封装到List中
 31      * @param obj PO所要保存值对象
 32      * @return 保存记录数 0:为保存失败
 33      * */
 34     public void save(List<T> ls);
 35     
 36     /**
 37      * 删除表中所有数据,通过Object.ClassName得到表名称
 38      * @param tableName删除表名称
 39      * @return 删除记录数据
 40      * */
 41     public int deleteAll(String tableName);
 42     
 43     public void deleteById(PK id);
 44     
 45     /**  
 46      * 根据查询语句,返回对象列表  
 47      *   
 48      * @param hql  
 49      *            查询语句  
 50      * @return 符合查询语句的对象列表 
 51      */  
 52     public List find(String hql);
 53     
 54     /**  
 55      * 返回指定起始位置,指定条数的对象  
 56      *   
 57      * @param hql  
 58      *            查询语句  
 59      * @param firstResult  
 60      *            起始位置  
 61      * @param maxResults  
 62      *            最多纪录数  
 63      * @return list 结果列表  
 64      */  
 65     //public List<T> find(String hql,int firstResult,int maxResults);
 66     
 67     /**  
 68      * 返回指定起始位置,指定条数的对象  
 69      *   
 70      * @param hql  
 71      *            查询语句  
 72      * @param pageNo  
 73      *            页数  
 74      * @return list 结果列表  
 75      */  
 76     public List<T> find(String hql,int pageNo,int maxResults);
 77     
 78     /**  
 79      * 查询语句需要的条件参数。通过map传递  
 80      *   
 81      * @param hql  
 82      *            查询语句  
 83      * @param map  
 84      *            参数  
 85      * @param firstResult  
 86      *            起始位置  
 87      * @param maxResults  
 88      *            最多纪录数  
 89      * @return list 结果列表  
 90      */  
 91     //public List<T> find(String hql, Map map, int firstResult,int maxResults);
 92     
 93     /**  
 94      * 查询语句需要的条件参数。通过map传递  
 95      *   
 96      * @param hql  
 97      *            查询语句  
 98      * @param map  
 99      *            参数  
100      * @param pageNo  
101      *            页数 
102      */  
103     public List<T> find(String hql, Map map, int pageNo,int maxResults);
104     
105     /**  
106      * 根据查询语句,返回对象列表  
107      *   
108      * @param hql  
109      *            查询语句  
110      * @return 符合查询语句的对象列表 
111      */  
112     public List<T> find(String hql, Map map);
113     
114     
115     /**  
116      * 通过Hql 执行update/delete操作  
117      *   
118      * @param hql  
119      * @return  
120      */  
121     public int executeUpdate(String hql);
122     
123     /**  
124      * 查询表中所有记录  
125      */ 
126     public List<T> findAll() ;
127     
128     /**  
129      * 通过 DetachedCriteria 进行查询指定查询条数
130      * @param firstResult  
131      *            起始位置  
132      * @param maxResults  
133      *            最多纪录数 
134      * @param dc 
135      * 
136      * @return 符合查询语句的对象列表
137      */  
138     public List<T> findByCriteria(DetachedCriteria dc,int firstResult, int maxResults);
139     
140     /**
141      * 统计符合查询语句的条数
142      * @param dc 
143      * */
144     public int countByCriteria(DetachedCriteria dc);
145     
146     /**  
147      * 通过Hql 执行update/delete操作 带条件查询
148      *   
149      * @param hql  
150      * @return  
151      */ 
152     public int executeUpdate(String hql, Map pMap);
153     
154     /**
155      * 删除obj指定ID记录,通过捕捉异常来判断是否删除成功
156      * @param obj 指定ID记录数
157      * */
158     public void delete(T obj);
159     
160     /**
161      * 根据ID从内存中加载记录
162      * @param aclass 类
163      * @param id 可以为任意类型
164      * */
165     public T load(PK id) ;
166     
167     /**
168      * 加载数据
169      * */
170     public T get(PK id);
171     
172     public Object getObj(Class cls,PK id);
173     
174     /**
175      * 保存或修改
176      * @param obj 保存对象
177      * */
178     public void saveOrUpdate(T obj);
179     
180     public void saveOrUpdate(List<T> lsj);
181     /**
182      * 更新记录
183      * @param obj 保存对象
184      * */
185     public void update(T obj);
186     /**
187      * 更新记录
188      * @param obj 保存对象
189      * */
190     public int update(String hql);
191     /**  
192      * TODO count hql 方法 . 带条件 
193      */  
194     public int count(String hql, Map params);
195     
196     /**  
197      * TODO count hql 方法
198      */  
199     public Integer count(String hql);
200     
201     /**
202      * 根据hql删除记录
203      * @param hql 删除语句
204      * @param map 条件参数
205      * @return 删除条数
206      * */
207     public int delete(String hql,Map map);
208     
209     /**
210      * 根据hql删除记录
211      * @param hql 删除语句
212      * @param map 条件参数
213      * @return 删除条数
214      * */
215     public int delete(String hql);
216     
217     /**
218      * 根据hql语句,更新记录部分字段
219      * @param hql 更新语句
220      * @param map 更新参数及条件
221      * @return 返回值大于0则更新成功,否则更新失败
222      * */
223     public int update(String hql,Map map);
224     
225     /**
226      * 返回Object List数组
227      * @param hql
228      * @param map        hql中的参数和参数值
229      * @param pageNo     页码
230      * @param maxResults 每页显示最大条数
231      * @return
232      */
233     public List findObj( String hql, Map map, int pageNo, int maxResults);
234     
235     /**
236      * 返回Object List数组
237      * @param hql
238      * @return
239      */
240     public List findObj( String hql);
241     
242     /**
243      * 返回Object List数组
244      * @param hql
245      * @param map        hql中的参数和参数值
246      * @return
247      */
248     public List findObj( String hql, Map map);
249     
250     /**
251      * 
252      * @功能描述: 查询
253      * @param firstResult首条数据位数
254      * @param maxResult  每次取出最大条数
255      * @param criterion
256      * @return
257      * @throws DataAccessException   
258      * @return:List<T> 
259      * @创建人:宫长明
260      * @创建时间:May 28, 2010 4:14:31 PM
261      */
262     public List<T> findByCriteria( int firstResult,  int maxResults,  Criterion... criterion) ;
263     
264     /**
265      * 
266      * @功能描述: 查义
267      * @param firstResult   首条查询位置
268      * @param maxResults    第次查询最大数  小于0查询所有
269      * @param sortProperty  排序字段
270      * @param ascend        排序方法  true: ASC fasle: DESC
271      * @param criterion     
272      * @return   
273      * @return:List<T> 
274      * @创建人:宫长明
275      * @创建时间:May 28, 2010 4:14:37 PM
276      */
277     public List<T> findByCriteria( int firstResult,  int maxResults,  String sortProperty,  boolean ascend,  Criterion... criterion);
278     
279     /**
280      * 
281      * @功能描述: 
282      * @param criterion
283      * @return
284      * @throws DataAccessException   
285      * @return:List<T> 
286      * @创建人:宫长明
287      * @创建时间:May 28, 2010 4:14:41 PM
288      */
289     public List<T> findByCriteria( Criterion...criterion); 
290     //throws DataAccessException;
291     
292     /**
293      * 
294      * @功能描述: 
295      * @param criterion
296      * @return
297      * @throws DataAccessException   
298      * @return:int 
299      * @创建人:宫长明
300      * @创建时间:May 28, 2010 4:14:45 PM
301      */
302     public int countByCriteria( Criterion... criterion) ;
303     
304     /**
305      * @功能描述: 根据List删除数据
306      * @param obj List<T>
307      * @创建人:宫长明
308      * @创建时间:2011-4-8 上午09:15:05
309      */
310     public void deleteByList(List<T> obj);
311     
312     /**
313      * @功能描述: 合并重复obj后保存或添加
314      * @param obj
315      * @创建人:王树峰
316      * @创建时间:2011-4-8 下午03:19:03
317      */
318     public void saveOrUpdateMerge(T obj);
319     
320     /**
321      * 
322     * @Title: saveOrUpdateClear 
323     * @Description: 多了一句话.clear()
324     * @return: void
325     * @param326     * @throws
327      */
328     public void saveOrUpdateClear(T obj);
329     
330     public T mergeObj(T obj);
331 }
  1 import java.io.Serializable;
  2 import java.lang.reflect.ParameterizedType;
  3 import java.sql.SQLException;
  4 import java.util.ArrayList;
  5 import java.util.List;
  6 import java.util.Map;
  7 
  8 import org.hibernate.Criteria;
  9 import org.hibernate.HibernateException;
 10 import org.hibernate.Query;
 11 import org.hibernate.Session;
 12 import org.hibernate.criterion.Criterion;
 13 import org.hibernate.criterion.DetachedCriteria;
 14 import org.hibernate.criterion.Order;
 15 import org.hibernate.criterion.Projections;
 16 
 17 
 18 /**
 19  * 
 20  * @类描述:  Hibernate Dal 基本方法
 21  * @创建人:宫长明   
 22  * @创建时间:May 28, 2010 4:11:57 PM  
 23  * @项目名:办公用品  
 24  * @版本信息:V 1.0  
 25  * @Copyright (c) 北京开诚阳光科技有限公司-版权所有 V 2010.0
 26  */
 27 @SuppressWarnings("unchecked")
 28 public class BaseDaoHibernate<T,PK extends Serializable> extends HibernateDaoSupport implements IBaseDao<T,PK>{
 29     
 30     private final Class<T> aclass;
 31     
 32     
 33     public BaseDaoHibernate(){
 34         this.aclass = (Class<T>)((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
 35     }
 36 
 37     public int count(final String hql,final Map mparams) {
 38         
 39         List tempList = this.getHibernateTemplate().executeFind(new HibernateCallback(){
 40             public List doInHibernate(Session session) throws HibernateException, SQLException {
 41                 
 42                 StringBuffer countQuery = new StringBuffer("select count(*) ");
 43                 countQuery.append(hql);
 44                 Query query = session.createQuery(countQuery.toString());
 45                 String params[] = query.getNamedParameters();
 46                 for(int i=0;i<params.length;i++){
 47                     query.setParameter(params[i], mparams.get(params[i]));
 48                 }
 49                 List result = query.list();
 50                 return result;
 51             }
 52         });
 53         
 54         Object obj = tempList!=null&&tempList.size()>0?tempList.get(0):0;
 55         if (obj instanceof Long) {
 56             Integer count =    Integer.valueOf(String.valueOf(obj));
 57             return count;
 58         }else{
 59             Integer count = Integer.valueOf(String.valueOf(obj));
 60             return count.intValue();
 61         }
 62     }
 63 
 64     public Integer count(String hql) {
 65         List<Object> result = getHibernateTemplate().find("select count(*) "+hql);
 66         Object obj = result.get(0);
 67         if(obj instanceof Integer){
 68             Integer count =    (Integer)obj;
 69             return count;
 70         }else{
 71             Long count = (Long)obj;
 72             return count.intValue();
 73         }
 74     }
 75 
 76     public int countByCriteria(DetachedCriteria dc) {
 77         
 78         return 0;
 79     }
 80 
 81     public void delete(final T obj) {
 82         getHibernateTemplate().execute(new HibernateCallback(){
 83             public Object doInHibernate(Session session) throws HibernateException, SQLException {
 84                 session.clear();
 85                 session.delete(obj);
 86                 return null;
 87             }
 88 
 89         });
 90     }
 91     
 92     public void deleteByList(final List<T> obj) {
 93         getHibernateTemplate().execute(new HibernateCallback(){
 94             public Object doInHibernate(Session session) throws HibernateException, SQLException {
 95                 session.clear();
 96                 for(T t:obj){
 97                     session.delete(t);
 98                 }
 99                 return null;
100             }
101             
102         });
103     }
104 
105     public int deleteAll(final String tableName) {
106         
107         StringBuffer hql = new StringBuffer("delete from ");
108         hql.append(tableName);
109         return executeUpdate(hql.toString());
110     }
111 
112     public int executeUpdate(final String hql) {
113         
114         Object obj = getHibernateTemplate().execute(new HibernateCallback(){
115             public Object doInHibernate(Session session) throws HibernateException, SQLException {
116                 
117                 Query query = session.createQuery(hql);
118                 int result = 0 ; 
119                 result = query.executeUpdate();
120                 getHibernateTemplate().flush();
121                 return result;
122             }
123         });
124         if(obj!=null)
125             return ((Integer)obj).intValue();
126         else
127             return 0;
128     }
129 
130     public int executeUpdate(final String hql,final Map pMap) {
131         
132         Object obj = getHibernateTemplate().execute(new HibernateCallback(){
133             public Object doInHibernate(Session session) throws HibernateException, SQLException {
134                 
135                 Query query = session.createQuery(hql);
136                 String params[] = query.getNamedParameters();
137                 for(int i=0;i<params.length;i++){
138                     query.setParameter(params[i], pMap.get(params[i]));
139                 }
140                 int result = 0;
141                 result = query.executeUpdate();
142                 getHibernateTemplate().flush();
143                 return result;
144             }
145         });
146         if(obj!=null)
147             return ((Integer)obj).intValue();
148         else
149             return 0;
150     }
151 
152     public List<T> find(final String hql) {
153         return getHibernateTemplate().find(hql);
154     }
155     
156     public List<T> findObj(final String hql) {
157         return getHibernateTemplate().find(hql);
158     }
159 
160     public List<T> find(final String hql, final Map map) {
161         return getHibernateTemplate().executeFind(new HibernateCallback(){
162             public List<T> doInHibernate(Session session) throws HibernateException, SQLException {
163                 
164                 Query query = session.createQuery(hql);
165                 String[] pamars = query.getNamedParameters();  
166                 for(int i=0;i<pamars.length;i++){
167                     query.setParameter(pamars[i], map.get(pamars[i]));
168                 }
169                 List<T> results = new ArrayList();
170                 results = query.list();
171                 return results;
172             }
173         });
174     }
175     
176     public List findObj(final String hql, final Map map) {
177         return getHibernateTemplate().executeFind(new HibernateCallback(){
178             public List<T> doInHibernate(Session session) throws HibernateException, SQLException {
179                 
180                 Query query = session.createQuery(hql);
181                 String[] pamars = query.getNamedParameters();  
182                 for(int i=0;i<pamars.length;i++){
183                     query.setParameter(pamars[i], map.get(pamars[i]));
184                 }
185                 List<T> results = new ArrayList();
186                 results = query.list();
187                 return results;
188             }
189         });
190     }
191 
192     public List<T> findAll() throws DataAccessException {
193         return findByCriteria();
194     }
195     
196     public List<T> findByCriteria(DetachedCriteria dc, int firstResult, int maxResults) {
197         return null;
198     }
199 
200     public T get(PK id) {
201         return (T)getHibernateTemplate().get(aclass, id);
202     }
203     
204     public Object getObj(Class cls,PK id) {
205         return (T)getHibernateTemplate().get(cls, id);
206     }
207 
208     public T load(PK id) throws DataAccessException {
209         
210         return (T)getHibernateTemplate().load(aclass, id);
211     }
212 
213     public void save(T obj) {//1
214         
215         this.getHibernateTemplate().save(obj);
216     }
217     
218     public void saveByObj(T obj) {
219         
220         this.getHibernateTemplate().save(obj);
221     }
222 
223     public void save(List<T> ls) {
224         
225         this.getHibernateTemplate().saveOrUpdateAll(ls);
226         getHibernateTemplate().flush();
227     }
228 
229     public void saveOrUpdateMerge(T obj)
230     {
231         obj=(T)this.getHibernateTemplate().merge(obj);
232         this.getHibernateTemplate().saveOrUpdate(obj);
233         getHibernateTemplate().flush();
234         getHibernateTemplate().clear();
235     }
236     
237     public void saveOrUpdate(T obj) {
238         this.getHibernateTemplate().saveOrUpdate(obj);
239         getHibernateTemplate().flush();
240     }
241     
242     public void saveOrUpdateClear(T obj) {
243         this.getHibernateTemplate().saveOrUpdate(obj);
244         getHibernateTemplate().flush();
245         getHibernateTemplate().clear();
246     }
247     public void saveOrUpdate(List<T> lsj) {
248         this.getHibernateTemplate().saveOrUpdateAll(lsj);
249         getHibernateTemplate().flush();
250     }
251 
252     public void update(T obj) {
253         this.getHibernateTemplate().update(obj);
254         getHibernateTemplate().flush();
255     }
256     
257     public HibernateTemplate getHibTemplate(){
258         return this.getHibernateTemplate();
259     }
260 
261     public int delete(String hql, Map map) {
262         return executeUpdate(hql, map);
263     }
264 
265     public int update(String hql, Map map) {
266         return executeUpdate(hql, map);
267     }
268 
269     public int update(String hql) {
270         return executeUpdate(hql);
271     }
272 
273     public int delete(String hql) {
274         return executeUpdate(hql);
275     }
276     
277     public List<T> find(final String hql,final int pageNo,final int maxResults) {
278         return getHibernateTemplate().executeFind(new HibernateCallback(){
279             public List<T> doInHibernate(Session session) throws HibernateException, SQLException {
280                 
281                 Query query = session.createQuery(hql);
282                 if(maxResults>0)
283                     query.setFirstResult((pageNo-1)*maxResults).setMaxResults(maxResults);
284                 List<T> results = query.list();
285                 return results;
286             }
287         });
288     }
289     
290     public List<T> find(final String hql,final Map map,final int pageNo,final int maxResults) {
291         return getHibernateTemplate().executeFind(new HibernateCallback(){
292             public List<T> doInHibernate(Session session) throws HibernateException, SQLException {
293                 
294                 Query query = session.createQuery(hql);
295                 String[] pamars = query.getNamedParameters();  
296                 for(int i=0;i<pamars.length;i++){
297                     query.setParameter(pamars[i], map.get(pamars[i]));
298                 }
299                 if(maxResults>0)
300                     query.setFirstResult((pageNo-1)*maxResults).setMaxResults(maxResults);
301                 List<T> results = new ArrayList();
302                 results = query.list();
303                 return results;
304             }
305         });
306     }
307     
308     public List findObj(final String hql,final Map map,final int pageNo,final int maxResults) {
309         
310         return getHibernateTemplate().executeFind(new HibernateCallback(){
311             public List<T> doInHibernate(Session session) throws HibernateException, SQLException {
312                 
313                 Query query = session.createQuery(hql);
314                 String[] pamars = query.getNamedParameters();  
315                 for(int i=0;i<pamars.length;i++){
316                     query.setParameter(pamars[i], map.get(pamars[i]));
317                 }
318                 if(maxResults>0)
319                     query.setFirstResult((pageNo-1)*maxResults).setMaxResults(maxResults);
320                 List<T> results = new ArrayList();
321                 results = query.list();
322                 return results;
323             }
324         });
325     }
326 
327     public void deleteById(final PK id) {
328         getHibernateTemplate().execute(new HibernateCallback(){
329             public Object doInHibernate(Session session) throws HibernateException, SQLException {
330                 session.delete(session.get(aclass, id));
331                 return null;
332             }
333 
334         });
335     }
336     
337     public List<T> findByCriteria(final int firstResult, final int maxResults, final Criterion... criterion) throws DataAccessException{
338         return findByCriteria(firstResult, maxResults, null, false, criterion);
339     }
340     
341     public List<T> findByCriteria(final int firstResult, final int maxResults, final String sortProperty, final boolean ascend, final Criterion... criterion){
342         return getHibernateTemplate().executeFind(new HibernateCallback(){
343             public List<T> doInHibernate(Session session) throws HibernateException, SQLException {
344                 Criteria crit = session.createCriteria(aclass);
345                 if(criterion != null){
346                     for(Criterion c : criterion){
347                         crit.add(c);
348                     }
349                 }
350                 if(firstResult > 0)
351                     crit.setFirstResult(firstResult);
352                 if(maxResults > 0)
353                     crit.setMaxResults(maxResults);
354                 if(sortProperty != null && sortProperty.trim().length() > 0){
355                     crit.addOrder(ascend ? Order.asc(sortProperty) : Order.desc(sortProperty));
356                 }
357                 return crit.list();
358             }
359 
360         });
361     }
362     
363     public List<T> findByCriteria(final Criterion...criterion) throws DataAccessException {
364         return findByCriteria(-1, -1, criterion);
365     }
366     
367     public Criteria getCriteria(){
368         return this.getSession().createCriteria(aclass);
369     }
370     
371     public int countByCriteria(final Criterion... criterion) throws DataAccessException{
372         Object obj = getHibernateTemplate().execute(new HibernateCallback(){
373             public Integer doInHibernate(Session session) throws HibernateException, SQLException {
374                 Criteria crit = session.createCriteria(aclass);
375                 for(Criterion c : criterion){
376                     crit.add(c);
377                 }
378                 crit.setProjection(Projections.rowCount());
379                 Integer total = (Integer)crit.uniqueResult();
380                 return total;
381             }
382 
383         });
384         if(obj!=null)
385             return (Integer)obj;
386         return 0;
387     }
388     
389      public T mergeObj(T obj){
390          return (T)this.getSession().merge(obj);
391      }
392 }

 

posted on 2016-06-02 21:13  如风105  阅读(3751)  评论(0编辑  收藏  举报

导航