搭建框架之后,在数据持久层封装一些通用的方法是很有必要的,除了hibernate原生的一些方法以外,我们还可以对分页查找,直接写sql等等查找方法进行封装,这样在构建应用的过程中,实现了代码复用和快速开发的目的。
下面是一个baseDao的示例。
1 package com.xxxx.common.dataservice.base;
2
3 import org.apache.poi.ss.formula.functions.T;
4 import org.springframework.dao.DataAccessException;
5
6 import java.io.Serializable;
7 import java.util.Collection;
8 import java.util.List;
9 import java.util.Map;
10
11 /**
12 * 框架基础Dao接口
13 * <p/>
14 * 包含hibernate基本的增,删,改。
15 * 封装查询方法:
16 * 1.queryByMap,通过map键值对设置参数进行对象查询。
17 * 2.queryByJdbc,通过SQL查询;
18 * 3.queryByHql,通过HQL 查询。
19 *
20 */
21 public interface BaseDao {
22
23 /**
24 * HQL格式的from条件语句
25 *
26 * @param clazz 查询对象类型
27 */
28 public abstract <T> String getFromHql(Class<T> clazz);
29
30 /**
31 * 新增对象
32 *
33 * @param entity 持久化对象
34 */
35 public abstract void save(Object entity);
36
37 /**
38 * 新增或更新实体对象,若对象存在则更新,否者,新增记录。
39 *
40 * @param entity 持久化对象
41 */
42 public abstract void saveOrUpdate(Object entity);
43
44 /**
45 * 批量更新集合数据
46 *
47 * @param entities 持久化对象集合
48 * @param <E>
49 */
50 public abstract <E> void saveOrUpdateAll(Collection<E> entities);
51
52 /**
53 * 更新数据
54 *
55 * @param sql sql语句
56 * @param args 参数
57 */
58 public abstract void updateSql(String sql, Object... args);
59
60
61 /**
62 * 更新数据
63 *
64 * @param entity 持久化对象
65 */
66 public abstract void update(Object entity);
67
68 /**
69 * 删除对象
70 *
71 * @param entity 持久化对象
72 */
73 public abstract void delete(Object entity);
74
75 /**
76 * 根据Id删除对象
77 * @param id 对象ID
78 */
79 public abstract void deleteById(Class<T> clazz, Serializable id);
80
81 /**
82 * 批量删除集合数据
83 *
84 * @param entities 持久化对象集合
85 * @param <E>
86 */
87 public abstract <E> void deleteAll(Collection<E> entities);
88
89 /**
90 * 执行HQL语句
91 * @param hql HQL语句
92 */
93 public abstract void excuteHql(String hql);
94
95 /**
96 * 根据主键获取持久化对象
97 *
98 * @param clazz 返回持久化对象类型
99 * @param id 持久化对象主键
100 * @param <T> 泛型
101 * @return T 主键为Id的持久化对象
102 */
103 public abstract <T> T get(Class<T> clazz, Serializable id);
104
105
106 /**
107 * 清除指定的缓冲对象进行
108 *
109 * @param entity 从缓存中清楚的对象
110 */
111 public abstract void evict(Object entity);
112
113 /**
114 * 把缓存对象与数据同步
115 */
116 public abstract void flush();
117
118 /**
119 * *************************************查询***********************************************
120 */
121
122 /**
123 * 根据conditionMap中设置参数查询,返回list集合
124 *
125 * @param clazz 查询对象类型
126 * @param conditionMap 根据conditionMap里面放置的参数,查询条件:<code>conditionMap.put("userId","zhangsan")</code>
127 * 模糊查询用:<code>("uname","%"+uname+"%") </code>
128 * @param orderMap 根据orderMap里面放置的参数排序。
129 * <code>orderMap.put("propertyName","asc");orderMap.put("propertyName","desc");</code>
130 * @return 返回符合条件的对象集合
131 */
132
133 public abstract <T> List<T> queryByMap(Class<T> clazz, Map conditionMap, Map orderMap);
134
135 /**
136 * 带条件的查询.返回list集合的第一个元素
137 *
138 * @param clazz 返回持久化对象类型
139 * @param conditionMap 根据conditionMap里面放置的参数,查询条件:<code>conditionMap.put("userId","zhangsan")</code>
140 * 模糊查询用:<code>("uname","%"+uname+"%") </code>
141 * @param orderMap 根据orderMap里面放置的参数排序。
142 * <code>orderMap.put("propertyName","asc");orderMap.put("propertyName","desc");</code>
143 * @return 符合条件的持久化对象
144 */
145 public abstract <T> T queryByMapForUnique(Class<T> clazz, Map conditionMap, Map orderMap);
146
147
148 /**
149 * jdbc 查询 ,返回符合条件的集合
150 *
151 * @param sql sql查询语句 ,如:<code>select u.userid,u.username,u.age,u.password from t_user u where u.username=? and u.age=?</code>
152 * @param bindValue 对sql中条件<b>?</b>绑定的参数数组
153 * @param clazz 查询对象类型
154 * @return 符合条件的对象集合
155 */
156 public abstract <T> List<T> queryByJdbc(String sql, Object[] bindValue, Class<T> clazz);
157
158 /**
159 * jdbc 查询 ,返回符合条件的集合
160 *
161 * @param sql sql查询语句 ,如:<code>select u.userid,u.username,u.age,u.password from t_user u where u.username=? and u.age=?</code>
162 * @param bindValue 对sql中条件<b>?</b>绑定的参数数组
163 * @param clazz 查询对象类型,非Bean的对象,而是如String.class等
164 * @return 符合条件的对象集合
165 */
166 public abstract <T> List<T> queryByJdbcNoBean(String sql, Object[] bindValue, Class<T> clazz);
167
168 /**
169 * * jdbc 查询,返回符合条件的集合第一个元素
170 *
171 * @param sql sql查询语句 ,如:<code>select u.userid,u.username,u.age,u.password from t_user u where u.username=? and u.age=?</code>
172 * @param bindValue 对sql中条件<b>?</b>绑定的参数数组
173 * @param clazz 查询对象类型
174 * @param <T> 泛型
175 * @return 符合条件的对象集合的第一个元素
176 */
177 public abstract <T> T queryByJdbcForUnique(String sql, Object[] bindValue, Class<T> clazz);
178
179 /**
180 * jdbc 分页查询,返回分页辅助类对象
181 *
182 * @param sql sql查询语句
183 * @param p 分页辅助类
184 * @param clazz 查询对象类型
185 * @return 返回分页辅助类对象
186 */
187 public abstract Pagination queryJdbcForPagination(String sql, Pagination p, Class<T> clazz);
188
189 /**
190 * hql 查询,返回符合条件集合
191 *
192 * @param hql 查询语句:<code>"from User where userName=?,password=?"</code>
193 * @param bindValue 传入条件绑定参数数组
194 * @return 返回符合条件集合
195 */
196 public abstract <T> List<T> queryByHql(String hql, Object[] bindValue);
197
198 /**
199 * hql 查询,返回符合条件集合的第一个元素
200 *
201 * @param hql 查询语句:<code>"from User where userName=?,password=?"</code>
202 * @param bindValue 传入条件绑定参数数组
203 * @return 返回符合条件集合的第一个元素
204 */
205 public abstract Object queryByHqlForUnique(String hql, Object[] bindValue);
206
207 /**
208 * hql 查询,返回符合条件集合的前num个元素
209 *
210 * @param hql 查询语句:<code>"from User where userName=?,password=?"</code>
211 * @param bindValue 传入条件绑定参数数组
212 * @param num 元素个数
213 * @return 返回符合条件集合的前num个元素
214 */
215 public <T> List<T> queryLimitByHql(String hql, Object[] bindValue, int num);
216
217 /**
218 * hql 分页查询,返回分页辅助类对象
219 *
220 * @param hql hql查询语句:<code>"from User where userName=?,password=?"</code>
221 * @param bindValue 传入条件绑定参数数组
222 * @param p 分页辅助类
223 * @return 返回分页辅助类对象
224 */
225 public abstract Pagination queryByHqlForPagination(String hql, Object[] bindValue, Pagination p);
226
227 /**
228 * 分页查询所有数据,返回HibernatePage对象
229 *
230 * @param clazz 查询对象类型
231 * @param curPage 当前页码数
232 * @param pageSize 每页显示的条目数
233 * @return 返回HibernatePage对象
234 */
235 public <T> HibernatePage<T> queryAll(Class<T> clazz, int curPage, int pageSize);
236
237 /**
238 * hql 分页查询,返回HibernatePage对象
239 *
240 * @param hql hql查询语句:<code>"from User where userName=?,password=?"</code>
241 * @param cacheable 是否打开缓存,布尔量
242 * @param curPage 当前页码数
243 * @param pageSize 每页显示的条目数
244 * @param bindValue 传入条件绑定参数数组
245 * @return 返回HibernatePage对象
246 */
247 public <T> HibernatePage<T> doQuery(String hql, boolean cacheable, int curPage,
248 int pageSize, Object[] bindValue);
249
250 /**
251 * 查询符合要求的对象集合
252 * @param sql sql查询语句
253 * @param args 对sql中条件<b>?</b>绑定的参数数组
254 * @param rowMapper 把查询表中记录的 每个字段对应到entity/dto中的每个属性
255 * @param <T> 泛型
256 * @return 符合条件的对象集合
257 * @throws org.springframework.dao.DataAccessException
258 */
259 public abstract <T> List<T> query(String sql, Object[] args, org.springframework.jdbc.core.RowMapper<T> rowMapper) throws DataAccessException;
260
261 /**
262 * 查询符合要求的对象集合
263 * @param sql sql查询语句
264 * @param rowMapper 把查询表中记录的 每个字段对应到entity/dto中的每个属性
265 * @param args 参数
266 * @param <T> 泛型
267 * @return 符合条件的对象集合
268 * @throws org.springframework.dao.DataAccessException
269 */
270 public <T> List<T> query(String sql, org.springframework.jdbc.core.RowMapper<T> rowMapper, Object... args) throws DataAccessException;
271
272 /**
273 * 查询,如果查询结果有记录,则返回1,否则返回0
274 * @param sql sql查询语句
275 * @param args 参数
276 * @return int 1:有值返回,0:无值返回
277 * @throws org.springframework.dao.DataAccessException
278 */
279 public int queryForInt(String sql, Object... args) throws DataAccessException;
280
281 /**
282 * 查询
283 * @param sql sql查询语句
284 * @param requiredType
285 * @param <T> 泛型
286 * @return T
287 * @throws org.springframework.dao.DataAccessException
288 */
289 public <T> T queryForObject(String sql, Class<T> requiredType) throws DataAccessException;
290
291 /**
292 * 查询
293 * @param sql sql查询语句
294 * @return Map<String,Object> Map形式的结果集
295 * @throws org.springframework.dao.DataAccessException
296 */
297 public Map<String, Object> queryForMap(String sql) throws DataAccessException;
298
299 /**
300 * 执行sql语句
301 * @param sql sql语句
302 * @throws org.springframework.dao.DataAccessException
303 */
304 public void execute(String sql) throws DataAccessException;
305
306 /**
307 * 执行
308 * @param csc
309 * @param action
310 * @param <T> 泛型
311 * @return T 执行结果
312 * @throws org.springframework.dao.DataAccessException
313 */
314 public <T> T execute(org.springframework.jdbc.core.CallableStatementCreator csc, org.springframework.jdbc.core.CallableStatementCallback<T> action) throws DataAccessException;
315
316 /**
317 * 修改,如果修改成功,返回1,否则返回0
318 * @param sql 所要修改的sql语句
319 * @param args 修改的字段
320 * @return int 1:修改成功,0:修改失败
321 * @throws org.springframework.dao.DataAccessException
322 */
323 public int update(String sql, Object... args) throws DataAccessException;
324
325 /**
326 * 修改,如果修改成功,返回1,否则返回0
327 * @param sql 所要修改的sql语句
328 * @return int 1:修改成功,0:修改失败
329 * @throws org.springframework.dao.DataAccessException
330 */
331 public int update(String sql) throws DataAccessException;
332
333 /**
334 * 批量修改
335 * @param sql 所要修改的sql语句集合
336 * @return int[] 数组里的值是由1,0组成,1:修改成功,0:修改失败
337 * @throws org.springframework.dao.DataAccessException
338 */
339 public int[] batchUpdate(String[] sql) throws DataAccessException;
340
341 }
下面是接口实现
1 package com.xxxx.common.dataservice.base.impl;
2
3
4 import com.xxxx.common.dataservice.base.BaseDao;
5 import com.xxxx.common.dataservice.base.HibernatePage;
6 import com.xxxx.common.dataservice.base.Pagination;
7 import com.xxxx.common.dataservice.base.util.DateInterval;
8 import org.apache.poi.ss.formula.functions.T;
9 import org.hibernate.*;
10 import org.hibernate.annotations.common.util.Strinr;
11 import org.hibernate.criterion.Order;
12 import org.hibernate.criterion.Restrictions;
13 import org.hibernate.type.*;
14 import org.springframework.dao.DataAccessException;
15 import org.springframework.jdbc.core.CallableStatementCallback;
16 import org.springframework.jdbc.core.CallableStatementCreator;
17 import org.springframework.jdbc.core.JdbcTemplate;
18 import org.springframework.jdbc.core.RowMapper;
19 import org.springframework.jdbc.core.simple.ParameterizedBeanPropertyRowMapper;
20 import org.springframework.jdbc.core.simple.SimpleJdbcCall;
21 import org.springframework.orm.hibernate3.HibernateCallback;
22 import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
23 import org.springframework.stereotype.Repository;
24
25 import javax.annotation.Resource;
26 import java.io.Serializable;
27 import java.sql.SQLException;
28 import java.util.*;
29
30
31 /**
32 * 提供BaseDao的本地实现类
33 *
34 * @author xxy
35 * @version 1.0
36 * @since 1.0
37 */
38 @Repository("baseDao")
39 public class BaseDaoImpl extends HibernateDaoSupport implements BaseDao {
40
41
42 private int size = 0;
43 /**
44 * JdbcTemplate类
45 */
46 private JdbcTemplate jdbcTemplate;
47 /**
48 * SimpleJdbcCall类
49 */
50 private SimpleJdbcCall simpleJdbcCall;
51
52 /**
53 * 设置SimpleJdbcCall
54 * @param simpleJdbcCall
55 */
56 @Resource
57 public void setSimpleJdbcCall(SimpleJdbcCall simpleJdbcCall) {
58 this.simpleJdbcCall = simpleJdbcCall;
59 }
60
61 /**
62 * 设置jdbcTemplate
63 * @param jdbcTemplate
64 */
65 @Resource(name = "jdbcTemplate")
66 public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
67 this.jdbcTemplate = jdbcTemplate;
68 }
69
70 /**
71 * 设置sessionFactory
72 * @param
73 */
74 @Resource(name = "sessionFactory")
75 public void setSuperSessionFactory(SessionFactory sessionFactory) {
76 super.setSessionFactory(sessionFactory);
77 }
78
79 public <T> String getFromHql(Class<T> clazz) {
80 return "from " + clazz.getCanonicalName();
81 }
82
83 public void save(Object entity) {
84 super.getHibernateTemplate().save(entity);
85
86 }
87
88 public void saveOrUpdate(Object entity) {
89 super.getHibernateTemplate().saveOrUpdate(entity);
90
91 }
92
93 public <E> void saveOrUpdateAll(Collection<E> entities) {
94 super.getHibernateTemplate().saveOrUpdateAll(entities);
95 }
96
97 public void updateSql(String sql, Object... args) {
98 this.jdbcTemplate.update(sql, args);
99 }
100
101 public void update(Object entity) {
102 super.getHibernateTemplate().update(entity);
103
104 }
105
106
107 public void delete(Object entity) {
108 super.getHibernateTemplate().delete(entity);
109 }
110
111 public void deleteById(Class clazz, Serializable id) {
112 super.getHibernateTemplate().delete(getHibernateTemplate().load(clazz, id));
113 }
114
115 public <E> void deleteAll(Collection<E> entities) {
116 super.getHibernateTemplate().deleteAll(entities);
117 }
118
119 public void excuteHql(final String hql) {
120 super.getHibernateTemplate().execute(new HibernateCallback() {
121 public Object doInHibernate(Session session)
122 throws HibernateException, SQLException {
123 return session.createQuery(hql).executeUpdate();
124 }
125 });
126 }
127
128 public void evict(Object entity) {
129 super.getHibernateTemplate().evict(entity);
130 }
131
132
133 public void flush() {
134 super.getHibernateTemplate().flush();
135 }
136
137 public <T> T get(Class<T> clazz, Serializable id) {
138 return super.getHibernateTemplate().get(clazz, id);
139 }
140
141 /**
142 * 获取对象对应参数的类型
143 *
144 * @param bindValue 参数数组
145 * @return 对应类型数组
146 */
147
148 private Type[] typesFactory(Object[] bindValue) {
149 int count = bindValue.length;
150 Type[] types = new Type[count];
151 for (int i = 0; i < count; i++) {
152 if (bindValue[i].getClass().getName().endsWith("String")) {
153 types[i] = new StringType();
154 } else if (bindValue[i].getClass().getName().endsWith("Integer")) {
155 types[i] = new IntegerType();
156 } else if (bindValue[i].getClass().getName().endsWith("Float")) {
157 types[i] = new FloatType();
158 } else if (bindValue[i].getClass().getName().endsWith("Long")) {
159 types[i] = new LongType();
160 } else if (bindValue[i].getClass().getName().endsWith("Double")) {
161 types[i] = new DoubleType();
162 } else if (bindValue[i].getClass().getName().endsWith("Date")) {
163 types[i] = new TimestampType();
164 }
165 }
166 return types;
167 }
168
169 /**
170 * ************************** Query *************************************
171 */
172
173
174 public <T> List<T> queryByMap(final Class<T> clazz, final Map conditionMap, final Map orderMap) {
175 List<T> list = this.getHibernateTemplate().executeFind(
176 new HibernateCallback() {
177 public Object doInHibernate(Session session)
178 throws HibernateException, SQLException {
179 Criteria cri = session.createCriteria(clazz);
180
181 if (conditionMap != null) {
182 Set keySet = conditionMap.keySet();
183
184 for (Object key : keySet) {
185 if (key == null
186 || conditionMap.get(key) == null) {
187 continue;
188 }
189
190 if (conditionMap.get(key).getClass() == String.class && ((String) conditionMap.get(key)).indexOf("%") != -1) {
191 cri.add(Restrictions.like(key.toString(),
192 ((String) conditionMap.get(key))));
193 } else {
194 cri.add(Restrictions.eq(key.toString(),
195 conditionMap.get(key)));
196 }
197 }
198 }
199
200
201 if (orderMap != null) {
202 Set<String> keySet = orderMap.keySet();
203 for (String propertyName : keySet) {
204 if (propertyName == null
205 || orderMap.get(propertyName) == null) {
206 continue;
207 }
208
209 if (orderMap.get(propertyName).toString().toUpperCase()
210 .equals("ASC")) {
211 cri.addOrder(Order.asc(propertyName));
212 } else if (orderMap.get(propertyName).toString()
213 .toUpperCase().equals("DESC")) {
214 cri.addOrder(Order.desc(propertyName));
215 }
216
217 }
218 }
219
220 // cri.add(Restrictions.allEq(conditionMap));
221 List<T> e = cri.list();
222 return e;
223 }
224 });
225
226 return list;
227 }
228
229 /**
230 * 根据map<key,value>查询,结果分页返回。注意:支持的sql查询条件不包括between ... and ...
231 * @param clazz 要查询表单对应POJO的class对象
232 * @param conditionMap
233 * @param orderMap
234 * @param p
235 * @return
236 */
237 public Pagination queryByMapPagination(final Class<?> clazz, final Map conditionMap, final Map orderMap,final Pagination p) {
238 List<T> list = this.getHibernateTemplate().executeFind(
239 new HibernateCallback() {
240 public Object doInHibernate(Session session)
241 throws HibernateException, SQLException {
242 Criteria cri = session.createCriteria(clazz);
243
244 if (conditionMap != null) {
245 Set keySet = conditionMap.keySet();
246
247 for (Object key : keySet) {
248 if (key == null
249 || conditionMap.get(key) == null) {
250 continue;
251 }
252
253 if (conditionMap.get(key).getClass() == String.class && ((String) conditionMap.get(key)).indexOf("%") != -1) {
254 cri.add(Restrictions.like(key.toString(),
255 ((String) conditionMap.get(key))));
256 }//xu@2014-06-05 添加 btween and 时间区间查询
257 else if(conditionMap.get(key).getClass() == DateInterval.class ){
258 Date l = ((DateInterval)conditionMap.get(key)).getLeft();
259 Date r = ((DateInterval)conditionMap.get(key)).getRight();
260 if(l==null)
261 l = new Date(0);
262
263 if(r==null)
264 r = new Date(System.currentTimeMillis());
265
266 cri.add(Restrictions.between(key.toString(), l, r ));
267 } else {
268 cri.add(Restrictions.eq(key.toString(),
269 conditionMap.get(key)));
270
271 }
272 }
273 }
274
275
276 if (orderMap != null) {
277 Set<String> keySet = orderMap.keySet();
278 for (String propertyName : keySet) {
279 if (propertyName == null
280 || orderMap.get(propertyName) == null) {
281 continue;
282 }
283
284 if (orderMap.get(propertyName).toString().toUpperCase()
285 .equals("ASC")) {
286 cri.addOrder(Order.asc(propertyName));
287 } else if (orderMap.get(propertyName).toString()
288 .toUpperCase().equals("DESC")) {
289 cri.addOrder(Order.desc(propertyName));
290 }
291
292 }
293 }
294 size = cri.list().size();
295 cri.setFirstResult(p.getStart());
296 cri.setMaxResults(p.getLimit());
297 // cri.add(Restrictions.allEq(conditionMap));
298 List<T> e = cri.list();
299 return e;
300 }
301 });
302
303 Pagination pagination = new Pagination(p.getLimit());
304 pagination.setStart(p.getStart());
305 pagination.setTotalCount(size);
306 pagination.setRecords(list);
307 return pagination;
308 }
309
310 public <T> T queryByMapForUnique(final Class<T> clazz, final Map conditionMap, Map orderMap) {
311 List<T> list = this.queryByMap(clazz, conditionMap, null);
312
313 if (list != null && list.size() > 0)
314
315 return list.get(0);
316
317 return null;
318 }
319
320 /**
321 * 查询方法的基础方法
322 *
323 * @param selectClause 查询列信息
324 * @param condition 条件
325 * @param firstRow 起始记录
326 * @param maxRows 记录数
327 * @return List 符合条件的数据列表
328 * @throws RuntimeException
329 */
330 private List baseQuery(final String selectClause,
331 final Class clazz, final Object[] condition,
332 final String orderByStr, final int firstRow, final int maxRows) {
333 return (List) this.getHibernateTemplate().execute(
334 new HibernateCallback() {
335 public Object doInHibernate(Session session)
336 throws HibernateException, SQLException {
337 String hql = null;
338 Query query = null;
339
340 hql = new StringBuilder().append(selectClause == null ? "" : selectClause).append(" from ").append(clazz.getCanonicalName()).append(" model ").toString();
341 if (condition != null && condition.length > 0) {
342 String where = "";
343 for (int i = 0; i <= condition.length - 1; i++) {
344 if (condition[i] != null) {
345 if ("".equals(where)) {
346 where = "where ";
347 } else {
348 where += "and ";
349 }
350
351 where += "model." + condition[i] + " ";
352 }
353 }
354 hql += where;
355 }
356
357 if (!Stringr.isEmpty(orderByStr)) {
358 hql += " order by model." + orderByStr + " ";
359 }
360
361 query = session.createQuery(hql);
362
363 if (firstRow >= 0) {
364 query.setFirstResult(firstRow);
365 }
366 if (maxRows > 0) {
367 query.setMaxResults(maxRows);
368 }
369
370 return query.list();
371 }
372 });
373
374 }
375
376
377 /**
378 * 根据条件查出记录总数
379 *
380 * @param clazz 查询对象类
381 * @param condition 条件数组
382 * @return 记录条数
383 */
384 private int getTotalRow(Class clazz, Object[] condition) {
385 int totalRow = 0;
386 totalRow = ((Long) this.baseQuery("select count(*) ",
387 clazz, condition, null, 0, 0).iterator().next()).intValue();
388 return totalRow;
389 }
390
391 /**
392 * 分页查询 ,传一个HQL语句. 和一个参数数组.
393 *
394 * @param hql hql语句 :"from User where userName=?,password=?"
395 * @param bindValue 数组参数
396 * @param firstRow 分页起点
397 * @param maxRows 每页的记录总数
398 * @return 返回List集合
399 */
400
401 private List queryByHql(final String hql, final Object[] bindValue,
402 final int firstRow, final int maxRows) {
403 List list = this.getHibernateTemplate().executeFind(
404 new HibernateCallback() {
405 public Object doInHibernate(Session session)
406 throws HibernateException, SQLException {
407 Query query = session.createQuery(hql);
408
409 if (bindValue != null && bindValue.length >= 1) {
410 Type[] types = typesFactory(bindValue);
411 query.setParameters(bindValue, types);
412 }
413
414 if (firstRow >= 0) {
415 query.setFirstResult(firstRow);
416 if (maxRows > 0) {
417 query.setMaxResults(maxRows);
418 }
419 }
420
421 return query.list();
422
423 }
424 });
425 return list;
426 }
427
428 /**
429 * 分页查询 ,传一个HQL语句. 和一个参数数组.
430 *
431 * @param hql hql语句 :"from User where userName=?,password=?"
432 * @param bindValue 数组参数
433 * @param firstRow 分页起点
434 * @param maxRows 每页的记录总数
435 * @return Object 符合条件的数据对象
436 */
437
438 private Object queryByHqlForUnique(final String hql, final Object[] bindValue,
439 final int firstRow, final int maxRows) {
440 List list = this.getHibernateTemplate().executeFind(
441 new HibernateCallback() {
442 public Object doInHibernate(Session session)
443 throws HibernateException, SQLException {
444 Query query = session.createQuery(hql);
445
446 if (bindValue != null && bindValue.length >= 1) {
447 Type[] types = typesFactory(bindValue);
448 query.setParameters(bindValue, types);
449 }
450
451 if (firstRow >= 0) {
452 query.setFirstResult(firstRow);
453 if (maxRows > 0) {
454 query.setMaxResults(maxRows);
455 }
456 }
457
458 return query.list();
459
460 }
461 });
462
463 if (list != null && list.size() > 0) return list.get(0);
464 return null;
465 }
466
467 public <T> List<T> queryByHql(String hql, Object[] bindValue) {
468 return this.queryByHql(hql, bindValue, 0, 0);
469 }
470
471 public Object queryByHqlForUnique(String hql, Object[] bindValue) {
472 List list = this.queryByHql(hql, bindValue, 0, 0);
473
474 if (list != null && list.size() > 0)
475
476 return list.get(0);
477
478 return null;
479 }
480
481 public <T> List<T> queryLimitByHql(String hql, Object[] bindValue, int num) {
482 return this.queryByHql(hql, bindValue, 0, num);
483 }
484
485 public Pagination queryByHqlForPagination(final String hql, final Object[] bindValue,
486 Pagination p) {
487
488
489 if (p == null) {
490 p = new Pagination();
491 }
492
493 p.setTotalCount(this.getTotalRowHql(hql, bindValue));
494 List result = this.queryByHql(hql, bindValue, p
495 .getStart(), p.getLimit());
496 p.setRecords(result);
497 return p;
498 }
499
500 private int getTotalRowHql(String hql, final Object[] bindValue) {
501 int totalRow = 0;
502 int start = hql.indexOf("from");
503 totalRow = ((Long) this.queryByHql(
504 "select count(*) " + hql.substring(start, hql.length()),
505 bindValue, 0, 0).iterator().next()).intValue();
506 return totalRow;
507 }
508
509 public <T> HibernatePage<T> queryAll(Class<T> clazz, int curPage, int pageSize) {
510 return new HibernatePage<T>(getFromHql(clazz), getSession(), true, curPage, pageSize);
511 }
512
513 public <T> HibernatePage<T> doQuery(String hql, boolean cacheable, int curPage, int pageSize, Object[] bindValue) {
514 return new HibernatePage<T>(hql, getSession(), cacheable, curPage, pageSize, bindValue);
515 }
516
517 /*public void doHql(String hql){
518 Session session = super.getSessionFactory().openSession();
519 Transaction tx = session.beginTransaction();
520 session.createQuery(hql).executeUpdate();
521 tx.commit();
522 session.close();
523 }*/
524 /**
525 * ************JDBC*********************
526 */
527
528 public <T> List<T> queryByJdbc(String sql, Object[] bindValue, Class<T> clazz) {
529 return this.jdbcTemplate.query(sql, bindValue,
530 ParameterizedBeanPropertyRowMapper.newInstance(clazz));
531 }
532
533 public <T> List<T> queryByJdbcNoBean(String sql, Object[] bindValue, Class<T> clazz) {
534 return this.jdbcTemplate.queryForList(sql,null,clazz);
535 }
536
537 public <T> T queryByJdbcForUnique(String sql, Object[] bindValue, Class<T> clazz) {
538 List<T> list = this.jdbcTemplate.query(sql, bindValue,
539 ParameterizedBeanPropertyRowMapper.newInstance(clazz));
540 if (list.size() > 0) {
541 return list.get(0);
542 }
543 return null;
544 }
545
546 public Pagination queryJdbcForPagination(String sql, Pagination p, Class clazz) {
547
548 String countSql = "select count(*) from (" + sql + ")f";
549 int totalRow = this.jdbcTemplate.queryForInt(countSql);
550 p = p == null ? new Pagination() : p;
551 p.setTotalCount(totalRow);
552 p.setRecords(queryByJDBC(sql, clazz, p.getStart(), p.getStart() + p.getLimit()));
553 return p;
554 }
555
556 private List queryByJDBC(String sql, Class clazz,
557 final int firstRow, final int maxRow) {
558
559 //如果maxRow大于零则说明要分页,那么调用分页sql,否则调用普通sql
560 if (maxRow > 0) {
561 String paginationSql = rebuildSqlForPagination(sql, firstRow, maxRow);
562 return this.queryByJdbc(paginationSql, null, clazz);
563 } else {
564 return this.queryByJdbc(sql, null, clazz);
565 }
566 }
567
568
569 /**
570 * 生成分页查询语句
571 *
572 * @param sql sql语句
573 * @param fRow 值小的行数
574 * @param mRow 值大的行数
575 * @return String 查询语句
576 */
577 private String rebuildSqlForPagination(String sql, int fRow, int mRow) {
578
579 //生成分页StringBuffer
580 StringBuffer paginationSql = new StringBuffer("select * from(");
581 paginationSql.append("select pagination.*, rownum rownumber from(");
582 paginationSql.append(sql);
583 paginationSql.append(")pagination) ");
584 paginationSql.append("where rownumber > ");
585 paginationSql.append(fRow);
586 paginationSql.append(" and rownumber <= ");
587 paginationSql.append(mRow);
588
589 return paginationSql.toString();
590
591 }
592
593 public <T> List<T> query(String sql, Object[] args, RowMapper<T> rowMapper) throws DataAccessException {
594 return this.jdbcTemplate.query(sql, args, rowMapper);
595 }
596
597 public <T> List<T> query(String sql, RowMapper<T> rowMapper, Object... args) throws DataAccessException {
598 return this.jdbcTemplate.query(sql, rowMapper, args);
599 }
600
601 public int update(String sql, Object... args) throws DataAccessException {
602 return this.jdbcTemplate.update(sql, args);
603 }
604
605 public int queryForInt(String sql, Object... args) throws DataAccessException {
606 return this.jdbcTemplate.queryForInt(sql, args);
607 }
608
609
610 public void execute(String sql) throws DataAccessException {
611 this.jdbcTemplate.execute(sql);
612 }
613
614
615 public <T> T queryForObject(String sql, Class<T> requiredType) throws DataAccessException {
616 return this.jdbcTemplate.queryForObject(sql, requiredType);
617 }
618
619
620 public <T> T execute(CallableStatementCreator csc, CallableStatementCallback<T> action) throws DataAccessException {
621 return this.jdbcTemplate.execute(csc, action);
622 }
623
624
625 public Map<String, Object> queryForMap(String sql) throws DataAccessException {
626 return this.jdbcTemplate.queryForMap(sql);
627 }
628
629
630 public int update(String sql) throws DataAccessException {
631 return this.jdbcTemplate.update(sql);
632 }
633
634 public int[] batchUpdate(String[] sql) throws DataAccessException {
635 return this.jdbcTemplate.batchUpdate(sql);
636 }
637
638 }
下面是分页的两个封装
1 package com.xxxx.common.dataservice.base;
2
3
4 import org.hibernate.HibernateException;
5 import org.hibernate.Query;
6 import org.hibernate.Session;
7 import org.springframework.util.Assert;
8
9 import java.io.Serializable;
10 import java.util.List;
11 import java.util.regex.Matcher;
12 import java.util.regex.Pattern;
13
14
15
16
17 public class HibernatePage<T> implements Serializable {
18 private static final long serialVersionUID = 1913490847094219152L;
19 private List<T> elements;
20 private int pageSize;
21 private int pageNumber;
22 private long totalElements = 0;
23
24 // public HibernatePage(String resultHql, Session session, boolean cacheable, Pagination pagination, Object... values){
25 // this(resultHql,session,cacheable,pagination.getPageNumber(),pagination.getPageSize(),values);
26 // }
27 public HibernatePage(String resultHql, Session session, boolean cacheable, int pageNumber, int pageSize, Object... values) {
28 Query resultQuery=session.createQuery(resultHql);
29 this.pageNumber = pageNumber;
30 this.pageSize = pageSize;
31 try {
32 String countHql = "select count(*) " + removeSelect(removeOrders(resultQuery.getQueryString()));
33 Query countQuery = session.createQuery(countHql);
34 if (cacheable) {
35 countQuery.setCacheable(true);
36 resultQuery.setCacheable(true);
37 }
38 for (int i = 0; i < values.length; i++) {
39 countQuery.setParameter(i, values[i]);
40 resultQuery.setParameter(i, values[i]);
41 }
42 this.totalElements = (Long) countQuery.uniqueResult();
43 if (Integer.MAX_VALUE == this.pageNumber || this.pageNumber > getLastPageNumber()) //last page
44 {
45 this.pageNumber = getLastPageNumber();
46 }
47 if (this.pageNumber < 1) {
48 this.pageNumber = 1;
49 }
50 elements = resultQuery.setFirstResult((this.pageNumber - 1) * this.pageSize).setMaxResults(this.pageSize).list();
51 } catch (HibernateException e) {
52 throw new RuntimeException(e);
53 }
54 }
55
56 public HibernatePage(Query resultQuery, Session session, boolean cacheable, int pageNumber, int pageSize, Object... values) {
57 this.pageNumber = pageNumber;
58 this.pageSize = pageSize;
59 try {
60 String countHql = "select count(*) " + removeSelect(removeOrders(resultQuery.getQueryString()));
61 Query countQuery = session.createQuery(countHql);
62 if (cacheable) {
63 countQuery.setCacheable(true);
64 resultQuery.setCacheable(true);
65 }
66 for (int i = 0; i < values.length; i++) {
67 countQuery.setParameter(i, values[i]);
68 resultQuery.setParameter(i, values[i]);
69 }
70 this.totalElements = (Long) countQuery.uniqueResult();
71 if (Integer.MAX_VALUE == this.pageNumber || this.pageNumber > getLastPageNumber()) //last page
72 {
73 this.pageNumber = getLastPageNumber();
74 }
75 if (this.pageNumber < 1) {
76 this.pageNumber = 1;
77 }
78 elements = resultQuery.setFirstResult((this.pageNumber - 1) * this.pageSize).setMaxResults(this.pageSize).list();
79 } catch (HibernateException e) {
80 throw new RuntimeException(e);
81 }
82 }
83
84 public HibernatePage(Query resultQuery, Query countQuery,Session session, boolean cacheable, int pageNumber, int pageSize, Object... values) {
85 this.pageNumber = pageNumber;
86 this.pageSize = pageSize;
87 try {
88 //String countHql = "select count(*) " + removeSelect(removeOrders(resultQuery.getQueryString()));
89 //Query countQuery = session.createQuery(countHql);
90 if (cacheable) {
91 countQuery.setCacheable(true);
92 resultQuery.setCacheable(true);
93 }
94 for (int i = 0; i < values.length; i++) {
95 countQuery.setParameter(i, values[i]);
96 resultQuery.setParameter(i, values[i]);
97 }
98 this.totalElements = (Long) countQuery.uniqueResult();
99 if (Integer.MAX_VALUE == this.pageNumber || this.pageNumber > getLastPageNumber()) //last page
100 {
101 this.pageNumber = getLastPageNumber();
102 }
103 if (this.pageNumber < 1) {
104 this.pageNumber = 1;
105 }
106 elements = resultQuery.setFirstResult((this.pageNumber - 1) * this.pageSize).setMaxResults(this.pageSize).list();
107 } catch (HibernateException e) {
108 throw new RuntimeException(e);
109 }
110 }
111
112 /**
113 * 构建HibernatePage对象,完成Hibernate的Query数据的分页处理
114 *
115 * @param resultHql Hibernate的Query对象
116 * @param total 统计总数
117 * @param pageNumber 当前页编码,从1开始,如果传的值为Integer.MAX_VALUE表示获取最后一页。
118 * 如果你不知道最后一页编码,传Integer.MAX_VALUE即可。如果当前页超过总页数,也表示最后一页。
119 * 这两种情况将重新更改当前页的页码,为最后一页编码。
120 * @param pageSize 每一页显示的条目数
121 */
122 public HibernatePage(String resultHql, Session session, boolean cacheable, long total, int pageNumber, int pageSize, Object... values) {
123 Query resultQuery=session.createQuery(resultHql);
124 this.pageNumber = pageNumber;
125 this.pageSize = pageSize;
126 int maxResSize = this.pageSize;
127 try {
128 String countHql = "select count(*) " + removeSelect(removeOrders(resultQuery.getQueryString()));
129 Query countQuery = session.createQuery(countHql);
130 if (cacheable) {
131 countQuery.setCacheable(true);
132 resultQuery.setCacheable(true);
133 }
134 for (int i = 0; i < values.length; i++) {
135 countQuery.setParameter(i, values[i]);
136 resultQuery.setParameter(i, values[i]);
137 }
138 long count = (Long) countQuery.uniqueResult();
139 this.totalElements = count < total ? count : total;
140 if (Integer.MAX_VALUE == this.pageNumber || this.pageNumber >= getLastPageNumber()) //last page
141 {
142 this.pageNumber = getLastPageNumber();
143 maxResSize = (int)(this.totalElements - (this.pageNumber - 1) * this.pageSize);
144 }
145 if (this.pageNumber < 1) {
146 this.pageNumber = 1;
147 }
148
149 elements = resultQuery.setFirstResult((this.pageNumber - 1) * this.pageSize).setMaxResults(maxResSize).list();
150 } catch (HibernateException e) {
151 throw new RuntimeException(e);
152 }
153 }
154
155 public HibernatePage(Query resultQuery, long total, int pageNumber, int pageSize) {
156 this.pageNumber = pageNumber;
157 this.pageSize = pageSize;
158 int maxResSize = this.pageSize;
159 try {
160 this.totalElements = total;
161 if (Integer.MAX_VALUE == this.pageNumber || this.pageNumber >= getLastPageNumber()) //last page
162 {
163 this.pageNumber = getLastPageNumber();
164 maxResSize = (int)(total - (this.pageNumber - 1) * this.pageSize);
165 }
166 if (this.pageNumber < 1) {
167 this.pageNumber = 1;
168 }
169
170 elements = resultQuery.setFirstResult((this.pageNumber - 1) * this.pageSize).setMaxResults(maxResSize).list();
171 } catch (HibernateException e) {
172 throw new RuntimeException(e);
173 }
174 }
175
176 /**
177 * 构建HibernatePage对象,完成Hibernate的分页处理
178 *
179 * @param elements 当前页面要显示的数据
180 * @param total 所有页面数据总数
181 * @param pageNumber 当前页编码,从1开始,如果传的值为Integer.MAX_VALUE表示获取最后一页。
182 * 如果你不知道最后一页编码,传Integer.MAX_VALUE即可。如果当前页超过总页数,也表示最后一页。
183 * 这两种情况将重新更改当前页的页码,为最后一页编码。
184 * @param pageSize 每一页显示的条目数
185 */
186 public HibernatePage(List elements, long total, int pageNumber, int pageSize) {
187 this.pageNumber = pageNumber;
188 this.pageSize = pageSize;
189 this.totalElements = total;
190
191 if (Integer.MAX_VALUE == this.pageNumber || this.pageNumber > getLastPageNumber()) //last page
192 {
193 this.pageNumber = getLastPageNumber();
194 }
195 if (this.pageNumber < 1) {
196 this.pageNumber = 1;
197 }
198
199 this.elements = elements;
200 }
201
202 public boolean isFirstPage() {
203 return getPageNumber() == 1;
204 }
205
206 public boolean isLastPage() {
207 return getPageNumber() >= getLastPageNumber();
208 }
209
210 public boolean hasNextPage() {
211 return getLastPageNumber() > getPageNumber();
212 }
213
214 public boolean hasPreviousPage() {
215 return getPageNumber() > 1;
216 }
217
218 public int getLastPageNumber() {
219 return (int)(totalElements % this.pageSize == 0 ? totalElements / this.pageSize : totalElements / this.pageSize + 1);
220 }
221
222 /**
223 * 返回List类型数据
224 *
225 * @return List数据源
226 */
227 public List<T> getElements() {
228 return elements;
229 }
230
231 public long getTotalElements() {
232 return totalElements;
233 }
234
235 public int getThisPageFirstElementNumber() {
236 return (getPageNumber() - 1) * getPageSize() + 1;
237 }
238
239 public long getThisPageLastElementNumber() {
240 int fullPage = getThisPageFirstElementNumber() + getPageSize() - 1;
241 return getTotalElements() < fullPage ? getTotalElements() : fullPage;
242 }
243
244 public int getNextPageNumber() {
245 return getPageNumber() + 1;
246 }
247
248 public int getPreviousPageNumber() {
249 return getPageNumber() - 1;
250 }
251
252 public int getPageSize() {
253 return pageSize;
254 }
255
256 public int getPageNumber() {
257 return pageNumber;
258 }
259
260 /*
261 * 去除select 子句,未考虑union的情况
262 *
263 */
264 private static String removeSelect(String hql) {
265 Assert.hasText(hql);
266 int beginPos = hql.toLowerCase().indexOf("from");
267 Assert.isTrue(beginPos != -1, " hql : " + hql + " must has a keyword 'from'");
268 return hql.substring(beginPos);
269 }
270
271 /*
272 * 去除orderby 子句
273 */
274 private static String removeOrders(String hql) {
275 Assert.hasText(hql);
276 Pattern p = Pattern.compile("order\\s*by[\\w|\\W|\\s|\\S]*", Pattern.CASE_INSENSITIVE);
277 Matcher m = p.matcher(hql);
278 StringBuffer sb = new StringBuffer();
279 while (m.find()) {
280 m.appendReplacement(sb, "");
281 }
282 m.appendTail(sb);
283 return sb.toString();
284 }
285 }
1 package com.xxxx.common.dataservice.base;
2
3
4 import java.io.Serializable;
5 import java.util.List;
6
7 /**
8 *分页辅助类
9 *
10 */
11 public class Pagination implements Serializable{
12 /**
13 * 记录总数
14 */
15 private int totalCount;
16 /**
17 * 记录数据集合
18 */
19 private List records;
20 /**
21 * 记录开始数
22 */
23 private int start;
24 /**
25 * 每页显示记录条数
26 */
27 private int limit;
28
29 public Pagination() {
30 this.totalCount = 0;
31 this.records = null;
32 this.start = 0;
33 this.limit = 15;
34
35 }
36
37 public Pagination(int limit) {
38 this.limit = limit;
39 }
40
41 /**
42 * 获取记录总数
43 * @return int 记录总数
44 */
45 public int getTotalCount() {
46 return totalCount;
47 }
48
49 /**
50 * 设置记录总数
51 * @param totalCount 记录总数
52 */
53 public void setTotalCount(int totalCount) {
54 this.totalCount = totalCount;
55 }
56
57 /**
58 * 获取数据记录
59 * @return List 数据记录
60 */
61 public List getRecords() {
62 return records;
63 }
64
65 /**
66 * 设置数据记录
67 * @param records 数据记录
68 */
69 public void setRecords(List records) {
70 this.records = records;
71 }
72
73 /**
74 * 获取记录开始数
75 * @return int 记录开始数
76 */
77 public int getStart() {
78 return start;
79 }
80
81 /**
82 * 设置记录开始数
83 * @param start 记录开始数
84 */
85 public void setStart(int start) {
86 this.start = start;
87 }
88
89 /**
90 * 获取每页显示记录条数
91 * @return int 每页显示记录条数
92 */
93 public int getLimit() {
94 return limit;
95 }
96
97 /**
98 * 设置每页显示记录条数
99 * @param limit 每页显示记录条数
100 */
101 public void setLimit(int limit) {
102 this.limit = limit;
103 }
104 }
下面是应用到的DateInterval
1 package com.xxxx.common.dataservice.base.util;
2
3 import java.util.Date;
4
5 /**
6 * To change this template use File | Settings | File Templates.
7 */
8 public class DateInterval {
9 private Date left;//左区间
10 private Date right;//右区间
11
12 public DateInterval() {
13
14 }
15
16 public DateInterval(Date left, Date right) {
17 this.left = left;
18 this.right = right;
19 }
20
21 public Date getLeft() {
22 return left;
23 }
24
25 public void setLeft(Date left) {
26 this.left = left;
27 }
28
29 public Date getRight() {
30 return right;
31 }
32
33 public void setRight(Date right) {
34 this.right = right;
35 }
36 }
然后就可以愉快的去进行数据库CRUD操作啦~