仅一行代码完成各种数据库操作,基于spring的HibernateTemplate

转自:http://www.oschina.net/code/snippet_561293_10813

在用到时,只需要继承自BaseHibernate,可以实现所有接口对于数据库的操作,增、删、改、查、分页、统计等。


[1].[代码] [Java]代码 跳至 [1] [2] [3]

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
 
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Property;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;
 
public class BaseHibernate {
    private static HibernateTemplate hibernateTemplate;
 
    @SuppressWarnings("static-access")
    public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
        this.hibernateTemplate = hibernateTemplate;
    }
 
    /**
     * 插入对象
     *
     * @param entity
     * @return
     */
    public int save(Object entity) {
        return (Integer) hibernateTemplate.save(entity);
    }
 
    /**
     * 删除对象
     *
     * @param entity
     */
    public void delete(Object entity) {
        hibernateTemplate.delete(entity);
    }
 
    /**
     * 修改对象
     *
     * @param entity
     */
    public void update(Object entity) {
        hibernateTemplate.update(entity);
    }
 
    /**
     * 根据ID查询对象
     *
     * @param entityClass
     *            类名,如:String.class
     * @param id
     *            ID值
     */
    public <T> T query(Class<T> entityClass, int id) {
        return hibernateTemplate.get(entityClass, id);
    }
 
    /**
     * 查询全部
     *
     * @param className
     *            类名
     * @return
     */
    @SuppressWarnings("unchecked")
    public <T> List<T> queryAll(Class<?> className) {
        return hibernateTemplate.find("from " + className.getName());
    }
 
    /**
     * 分页
     *
     * @param entityClass
     *            类名
     * @param index
     *            当前页数
     * @param size
     *            每页显示的大小
     * @param order
     *            排序类型
     * @param propertyName
     *            要排序的属性名
     * @return
     */
    @SuppressWarnings("unchecked")
    public <T> List<T> paging(final Class<?> entityClass, final int index,
            final int size, final Order order, final String... propertyName) {
        List<T> list = hibernateTemplate.executeFind(new HibernateCallback() {
            public Object doInHibernate(Session session)
                    throws HibernateException, SQLException {
                Criteria criteria = session.createCriteria(entityClass);
                if (propertyName != null && propertyName.length > 0) {
                    switch (order) {
                    case ASC:
                        criteria.addOrder(org.hibernate.criterion.Order
                                .asc(propertyName[0]));
                        break;
                    case DESC:
                        criteria.addOrder(org.hibernate.criterion.Order
                                .desc(propertyName[0]));
                        break;
                    }
                }
                criteria.setFirstResult((index - 1) * size);
                criteria.setMaxResults(size);
                return criteria.list();
            }
        });
        return list;
    }
 
    @SuppressWarnings("unchecked")
    public long getSumRecord(final Class<?> className) {
        List<Long> count = new ArrayList<Long>();
        count = hibernateTemplate.find("select COUNT(*) from "
                + className.getName());
        return count.size() > 0 ? (count.get(0)) : 0L;
    }
 
    /**
     * 获取总页数
     *
     * @param className
     *            类名
     * @param size
     *            每页显示的大小
     * @return
     */
    @SuppressWarnings("unchecked")
    public long sumPage(final Class<?> className, int size) {
        List<Long> count = new ArrayList<Long>();
        count = hibernateTemplate.find("select COUNT(*) from "
                + className.getName());
        return count.size() > 0 ? (count.get(0) - 1 + size) / size : 0L;
    }
 
    /**
     * 根据字段查询
     *
     * @param params
     *            字段列表
     * @param values
     *            值列表
     * @return
     */
    @SuppressWarnings("unchecked")
    public <T> List<T> queryByProperty(final Class<?> className,
            final Map<String, Object> params) {
        return hibernateTemplate.executeFind(new HibernateCallback() {
            public List<?> doInHibernate(Session session)
                    throws HibernateException, SQLException {
                Criteria criteria = session.createCriteria(className);
                for (String field : params.keySet())
                    criteria.add(Property.forName(field).eq(params.get(field)));
                return criteria.list();
            }
        });
    }
 
    /**
     * 根据字段查询可以分的页数
     *
     * @param className
     *            要查询的实体类
     * @param params
     *            属性列表
     * @param size
     *            每页显示的大小
     * @return
     */
    @SuppressWarnings("unchecked")
    public long queryByPropertyGetSumPage(final Class<?> className,
            final Map<String, Object> params, final int size) {
        List<Integer> object = hibernateTemplate
                .executeFind(new HibernateCallback() {
                    public Object doInHibernate(Session session)
                            throws HibernateException, SQLException {
                        Criteria criteria = session.createCriteria(className);
                        for (String field : params.keySet())
                            criteria.add(Property.forName(field).eq(
                                    params.get(field)));
                        criteria.setProjection(Projections.rowCount());
                        return criteria.list();
                    }
                });
        int count = object == null ? 0 : object.get(0);
        return count > 0 ? (count + size - 1) / size : 0L;
    }
 
    /**
     * 获取总记录数根据属性
     *
     * @param className
     * @param params
     * @param size
     * @return
     */
    @SuppressWarnings("unchecked")
    public long queryByPropertyGetSumRecord(final Class<?> className,
            final Map<String, Object> params) {
        List<Integer> object = hibernateTemplate
                .executeFind(new HibernateCallback() {
                    public Object doInHibernate(Session session)
                            throws HibernateException, SQLException {
                        Criteria criteria = session.createCriteria(className);
                        for (String field : params.keySet())
                            criteria.add(Property.forName(field).eq(
                                    params.get(field)));
                        criteria.setProjection(Projections.rowCount());
                        return criteria.list();
                    }
                });
        return object == null ? 0 : object.get(0);
    }
 
    /**
     * 根据字段查询并分页显示
     *
     * @param className
     *            要分页的实体类
     * @param params
     *            字段列表
     * @param index
     *            当前页
     * @param size
     *            每页显示的大小
     * @param order
     *            排序
     * @return
     */
    @SuppressWarnings("unchecked")
    public <T> List<T> queryByPropertyPaging(final Class<?> className,
            final Map<String, Object> params, final int index, final int size,
            final Order order, final String... field) {
        return hibernateTemplate.executeFind(new HibernateCallback() {
            public List<?> doInHibernate(Session session)
                    throws HibernateException, SQLException {
                Criteria criteria = session.createCriteria(className);
                for (String f : params.keySet())
                    criteria.add(Property.forName(f).eq(params.get(f)));
                if (field != null && field.length != 0) {
                    switch (order) {
                    case ASC:
                        criteria.addOrder(org.hibernate.criterion.Order
                                .asc(field[0]));
                        break;
                    case DESC:
                        criteria.addOrder(org.hibernate.criterion.Order
                                .desc(field[0]));
                        break;
                    }
                }
                criteria.setFirstResult((index - 1) * size);
                criteria.setMaxResults(size);
                return criteria.list();
            }
        });
    }
 
    /**
     * 保存或更新对象
     *
     * @param entity
     *            对象
     */
    public void saveOrUpdate(Object entity) {
        hibernateTemplate.saveOrUpdate(entity);
    }
 
    /**
     * 批量修改
     *
     * @param queryString
     *            HQL语句
     * @return 受影响行数
     */
    public int bulkUpdate(String queryString) {
        return hibernateTemplate.bulkUpdate(queryString);
    }
 
    /**
     * 批量修改
     *
     * @param queryString
     *            HQL语句
     * @param values
     *            参数的值
     * @return 受影响行数
     */
    public int bulkUpdate(String queryString, Object... values) {
        return hibernateTemplate.bulkUpdate(queryString, values);
    }
 
    /**
     * 批量删除
     *
     * @param collection
     *            要删除的集合
     */
    public void deleteAll(Collection<?> collection) {
        hibernateTemplate.deleteAll(collection);
    }
 
    /**
     * 模糊查询
     *
     * @param className
     *            类名
     * @param field
     *            字段名
     * @param value
     *            值
     * @param matchMode
     *            匹配模式:ANYWHERE->任意位置、END->结束、START->开始、EXACT->精确匹配
     */
    @SuppressWarnings("unchecked")
    public <T> List<T> Querylike(final Class<?> className, final String field,
            final String value, final MatchMode matchMode) {
        List objects = new ArrayList<Object>();
        objects = hibernateTemplate.executeFind(new HibernateCallback() {
            public Object doInHibernate(Session session)
                    throws HibernateException, SQLException {
                Criteria criteria = session.createCriteria(className);
                criteria.add(Property.forName(field).like(value, matchMode));
                return criteria.list();
            }
        });
        return objects;
    }
 
    /**
     * 执行hql查询语句
     *
     * @param hql
     *            hql语句
     * @param values
     *            值列表
     * @return
     */
    @SuppressWarnings("unchecked")
    public <T> Object executeQuery(final String hql, final Object... values) {
        return hibernateTemplate.execute(new HibernateCallback() {
 
            public Object doInHibernate(Session session)
                    throws HibernateException, SQLException {
                Query query = session.createQuery(hql);
                setParams(query, values);
                return query.list();
            }
        });
    }
 
    /**
     * 查询单个值
     *
     * @param hql
     *            hql语句
     * @param values
     *            参数列表
     * @return 返回单个值
     */
    @SuppressWarnings("unchecked")
    public <T> Object executeSacale(final String hql, final Object... values) {
        return hibernateTemplate.execute(new HibernateCallback() {
            public Object doInHibernate(Session session)
                    throws HibernateException, SQLException {
                Query query = session.createQuery(hql);
                setParams(query, values);
                query.setMaxResults(1);
                return query.uniqueResult();
            }
        });
    }
 
    /**
     * 执行hql删除、修改语句
     *
     * @param hql
     *            hql语句
     * @param values
     *            值列表
     * @return
     */
    @SuppressWarnings("unchecked")
    public int executNonQuery(final String hql, final Object... values) {
        return hibernateTemplate.execute(new HibernateCallback() {
            public Integer doInHibernate(Session session)
                    throws HibernateException, SQLException {
                Query query = session.createQuery(hql);
                setParams(query, values);
                return query.executeUpdate();
            }
        });
    }
 
    /**
     * 删除表数据
     * @param tableName 表名
     */
     
    @SuppressWarnings("unchecked")
    public void truncate(final String tableName) {
        hibernateTemplate.execute(new HibernateCallback() {
            public Object doInHibernate(Session session)
                    throws HibernateException, SQLException {
                session.createSQLQuery("truncate table " + tableName).executeUpdate();
                return new ArrayList();
            }
        });
 
    }
 
    private void setParams(Query query, Object... values) {
        if (!isEmptyOrNull(values)) {
            for (int i = 0; i < values.length; i++) {
                query.setParameter(i, values[i]);
            }
 
        }
    }
 
    /**
     * 判断值是否为空或
     *
     * @param values
     * @return
     */
    private boolean isEmptyOrNull(Object... values) {
        if (values == null || values.length == 0)
            return true;
        return false;
    }
 
}

[2].[代码] 排序类型 跳至 [1] [2] [3]

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
/**
 * 排序类型
 * @author cheng
 *
 */
public enum Order {
    /**
     * 升序排列
     */
    ASC,
    /**
     * 降序排列
     */
    DESC;

[3].[代码] 实例应用 跳至 [1] [2] [3]

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
//UsersDao interface
public interface UsersDao{ 
         /**
     * 根据属性查询
     * @param attrName 属性名
     * @param attrValues 属性值
     * @return Users集合
     */
    public List<Users> queryByProperty(Map<String, Object> propertys);
}
//UserDaoImpl
 
import java.util.List;
import java.util.Map;
 
import org.ps.dao.UsersDao;
import org.ps.entity.Users;
import org.ps.util.BaseHibernate;
import org.ps.util.Order;
 
public class UserDaoImpl extends BaseHibernate implements UsersDao {
 
public List<Users> queryByProperty(Map<String, Object> propertys) {
        return super.queryByProperty(Users.class, propertys);
    }
}
posted @ 2014-12-04 10:18  骑着骆驼逛沙漠  阅读(251)  评论(0编辑  收藏  举报