HibernateDao.java
http://my.oschina.net/lizy/blog/526769
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 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 |
Java代码 /** * Copyright (c) 2005-2010 springside.org.cn * * Licensed under the Apache License, Version 2.0 (the "License"); * * $Id: HibernateDao.java 1205 2010-09-09 15:12:17Z calvinxiu $ */ package com.dao.hibernate; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.math.NumberUtils; import org.hibernate.Criteria; import org.hibernate.Query; import org.hibernate.SessionFactory; import org.hibernate.criterion.CriteriaSpecification; import org.hibernate.criterion.Criterion; import org.hibernate.criterion.Disjunction; import org.hibernate.criterion.MatchMode; import org.hibernate.criterion.Order; import org.hibernate.criterion.Projection; import org.hibernate.criterion.Projections; import org.hibernate.criterion.Restrictions; import org.hibernate.impl.CriteriaImpl; import org.hibernate.transform.ResultTransformer; import org.springframework.util.Assert; import com.dao.hibernate.PropertyFilter.MatchType; import com.utils.ReflectionUtils; /** * 封装SpringSide扩展功能的Hibernat DAO泛型基类. * * 扩展功能包括分页查询,按属性过滤条件列表查询. 可在Service层直接使用,也可以扩展泛型DAO子类使用,见两个构造函数的注释. * * @param <T> * DAO操作的对象类型 * @param <PK> * 主键类型 * * @author calvin */ public class HibernateDao<T, PK extends Serializable> extends SimpleHibernateDao<T, PK> { /** * 用于Dao层子类的构造函数. 通过子类的泛型定义取得对象类型Class. eg. public class UserDao extends * HibernateDao<User, Long>{ } */ public HibernateDao() { super(); } /** * 用于省略Dao层, Service层直接使用通用HibernateDao的构造函数. 在构造函数中定义对象类型Class. eg. * HibernateDao<User, Long> userDao = new HibernateDao<User, * Long>(sessionFactory, User.class); */ public HibernateDao(final SessionFactory sessionFactory, final Class<T> entityClass) { super(sessionFactory, entityClass); } // -- 分页查询函数 --// /** * 分页获取全部对象. */ public Page<T> getAll(final Page<T> page) { return findPage(page); } /** * 按HQL分页查询. * * @param page * 分页参数. 注意不支持其中的orderBy参数. * @param hql * hql语句. * @param values * 数量可变的查询参数,按顺序绑定. * * @return 分页查询结果, 附带结果列表及所有查询输入参数. */ public Page<T> findPage(final Page<T> page, final String hql, final Object... values) { Assert.notNull(page, "page不能为空"); Query q = createQuery(hql, values); if (page.isAutoCount()) { long totalCount = countHqlResult(hql, values); page.setTotalCount(totalCount); } setPageParameterToQuery(q, page); List result = q.list(); page.setResult(result); return page; } /** * 按HQL分页查询. * * @param page * 分页参数. 注意不支持其中的orderBy参数. * @param hql * hql语句. * @param values * 命名参数,按名称绑定. * * @return 分页查询结果, 附带结果列表及所有查询输入参数. */ @SuppressWarnings("unchecked") public Page<T> findPage(final Page<T> page, final String hql, final Map<String, ?> values) { Assert.notNull(page, "page不能为空"); Query q = createQuery(hql, values); if (page.isAutoCount()) { long totalCount = countHqlResult(hql, values); page.setTotalCount(totalCount); } setPageParameterToQuery(q, page); List result = q.list(); page.setResult(result); return page; } /** * 按Criteria分页查询. * * @param page * 分页参数. * @param criterions * 数量可变的Criterion. * * @return 分页查询结果.附带结果列表及所有查询输入参数. */ @SuppressWarnings("unchecked") public Page<T> findPage(final Page<T> page, final Criterion... criterions) { Assert.notNull(page, "page不能为空"); Criteria c = createCriteria(criterions); if (page.isAutoCount()) { long totalCount = countCriteriaResult(c); page.setTotalCount(totalCount); } if(page.getPageNo() > page.getTotalPages()) { page.setPageNo(NumberUtils.toInt(Long.toString(page.getTotalPages()))); } setPageParameterToCriteria(c, page); List result = c.list(); page.setResult(result); return page; } /** * 设置分页参数到Query对象,辅助函数. */ protected Query setPageParameterToQuery(final Query q, final Page<T> page) { Assert.isTrue(page.getPageSize() > 0, "Page Size must larger than zero"); // hibernate的firstResult的序号从0开始 q.setFirstResult(page.getFirst() - 1); q.setMaxResults(page.getPageSize()); return q; } /** * 设置分页参数到Criteria对象,辅助函数. */ protected Criteria setPageParameterToCriteria(final Criteria c, final Page<T> page) { Assert.isTrue(page.getPageSize() > 0, "Page Size must larger than zero"); // hibernate的firstResult的序号从0开始 c.setFirstResult(page.getFirst() - 1); c.setMaxResults(page.getPageSize()); if (page.isOrderBySetted()) { String[] orderByArray = StringUtils.split(page.getOrderBy(), ','); String[] orderArray = StringUtils.split(page.getOrder(), ','); Assert.isTrue(orderByArray.length == orderArray.length, "分页多重排序参数中,排序字段与排序方向的个数不相等"); for (int i = 0; i < orderByArray.length; i++) { if (Page.ASC.equals(orderArray[i])) { c.addOrder(Order.asc(orderByArray[i])); } else { c.addOrder(Order.desc(orderByArray[i])); } } } return c; } /** * 执行count查询获得本次Hql查询所能获得的对象总数. * * 本函数只能自动处理简单的hql语句,复杂的hql查询请另行编写count语句查询. */ protected long countHqlResult(final String hql, final Object... values) { String countHql = prepareCountHql(hql); try { Long count = findUnique(countHql, values); return count; } catch (Exception e) { throw new RuntimeException("hql can't be auto count, hql is:" + countHql, e); } } /** * 执行count查询获得本次Hql查询所能获得的对象总数. * * 本函数只能自动处理简单的hql语句,复杂的hql查询请另行编写count语句查询. */ protected long countHqlResult(final String hql, final Map<String, ?> values) { String countHql = prepareCountHql(hql); try { Long count = findUnique(countHql, values); return count; } catch (Exception e) { throw new RuntimeException("hql can't be auto count, hql is:" + countHql, e); } } private String prepareCountHql(String orgHql) { String fromHql = orgHql; // select子句与order by子句会影响count查询,进行简单的排除. fromHql = "from " + StringUtils.substringAfter(fromHql, "from"); fromHql = StringUtils.substringBefore(fromHql, "order by"); String countHql = "select count(*) " + fromHql; return countHql; } /** * 执行count查询获得本次Criteria查询所能获得的对象总数. */ @SuppressWarnings("unchecked") protected long countCriteriaResult(final Criteria c) { CriteriaImpl impl = (CriteriaImpl) c; // 先把Projection、ResultTransformer、OrderBy取出来,清空三者后再执行Count操作 Projection projection = impl.getProjection(); ResultTransformer transformer = impl.getResultTransformer(); List<CriteriaImpl.OrderEntry> orderEntries = null; try { orderEntries = (List) ReflectionUtils.getFieldValue(impl, "orderEntries"); ReflectionUtils .setFieldValue(impl, "orderEntries", new ArrayList()); } catch (Exception e) { logger.error("不可能抛出的异常:{}", e.getMessage()); } // 执行Count查询 Long totalCountObject = Long.parseLong(c .setProjection(Projections.rowCount()).uniqueResult() .toString()); long totalCount = (totalCountObject != null) ? totalCountObject : 0; // 将之前的Projection,ResultTransformer和OrderBy条件重新设回去 c.setProjection(projection); if (projection == null) { c.setResultTransformer(CriteriaSpecification.ROOT_ENTITY); } if (transformer != null) { c.setResultTransformer(transformer); } try { ReflectionUtils.setFieldValue(impl, "orderEntries", orderEntries); } catch (Exception e) { logger.error("不可能抛出的异常:{}", e.getMessage()); } return totalCount; } // -- 属性过滤条件(PropertyFilter)查询函数 --// /** * 按属性查找对象列表,支持多种匹配方式. * * @param matchType * 匹配方式,目前支持的取值见PropertyFilter的MatcheType enum. */ public List<T> findBy(final String propertyName, final Object value, final MatchType matchType) { Criterion criterion = buildCriterion(propertyName, value, matchType); return find(criterion); } /** * 按属性过滤条件列表查找对象列表. */ public List<T> find(List<PropertyFilter> filters) { Criterion[] criterions = buildCriterionByPropertyFilter(filters); return find(criterions); } /** * 按属性过滤条件列表分页查找对象. */ public Page<T> findPage(final Page<T> page, final List<PropertyFilter> filters) { Criterion[] criterions = buildCriterionByPropertyFilter(filters); return findPage(page, criterions); } /** * 按属性条件参数创建Criterion,辅助函数. */ protected Criterion buildCriterion(final String propertyName, final Object propertyValue, final MatchType matchType) { Assert.hasText(propertyName, "propertyName不能为空"); Criterion criterion = null; // 根据MatchType构造criterion switch (matchType) { case EQ: criterion = Restrictions.eq(propertyName, propertyValue); break; case LIKE: criterion = Restrictions.like(propertyName, (String) propertyValue, MatchMode.ANYWHERE); break; case LE: criterion = Restrictions.le(propertyName, propertyValue); break; case LT: criterion = Restrictions.lt(propertyName, propertyValue); break; case GE: criterion = Restrictions.ge(propertyName, propertyValue); break; case GT: criterion = Restrictions.gt(propertyName, propertyValue); } return criterion; } /** * 按属性条件列表创建Criterion数组,辅助函数. */ protected Criterion[] buildCriterionByPropertyFilter( final List<PropertyFilter> filters) { List<Criterion> criterionList = new ArrayList<Criterion>(); for (PropertyFilter filter : filters) { if (!filter.hasMultiProperties()) { // 只有一个属性需要比较的情况. Criterion criterion = buildCriterion(filter.getPropertyName(), filter.getMatchValue(), filter.getMatchType()); criterionList.add(criterion); } else {// 包含多个属性需要比较的情况,进行or处理. Disjunction disjunction = Restrictions.disjunction(); for (String param : filter.getPropertyNames()) { Criterion criterion = buildCriterion(param, filter.getMatchValue(), filter.getMatchType()); disjunction.add(criterion); } criterionList.add(disjunction); } } return criterionList.toArray(new Criterion[criterionList.size()]); } } |