当前位置:   article > 正文

Hibernate Criteria查询之多表连接分页-2【分页封装】_hibernate 多表查询分页

hibernate 多表查询分页

分页相关实体类:

分页信息类:

  1. package org.accp.mhouse.pager;
  2. import java.io.Serializable;
  3. import java.util.List;
  4. /**分页信息类
  5. * 封装分页条件和结果
  6. * */
  7. public class PageInfo<T> implements Serializable {
  8. /**
  9. *
  10. */
  11. private static final long serialVersionUID = -4026351129192551762L;
  12. /*条件部分*/
  13. private Class<T> classzz;
  14. private int pageSize = 10;
  15. private int pageIndex = 1;
  16. private java.util.List<Condition> conditions = new java.util.ArrayList<Condition>();
  17. private java.util.List<Order> orders = new java.util.ArrayList<Order>();
  18. private java.util.List<Fetch> fetchs = new java.util.ArrayList<Fetch>();
  19. public java.util.List<Fetch> getFetchs() {
  20. return fetchs;
  21. }
  22. public void setFetchs(java.util.List<Fetch> fetchs) {
  23. this.fetchs = fetchs;
  24. }
  25. /*分页结果部分*/
  26. private int recordCount;
  27. private int pageCount;
  28. private java.util.List<T> result;
  29. public Class<T> getClasszz() {
  30. return classzz;
  31. }
  32. public void setClasszz(Class<T> classzz) {
  33. this.classzz = classzz;
  34. }
  35. public int getPageSize() {
  36. return pageSize;
  37. }
  38. public void setPageSize(int pageSize) {
  39. this.pageSize = pageSize;
  40. }
  41. public int getPageIndex() {
  42. return pageIndex;
  43. }
  44. public void setPageIndex(int pageIndex) {
  45. this.pageIndex = pageIndex;
  46. }
  47. public java.util.List<Condition> getConditions() {
  48. return conditions;
  49. }
  50. public void setConditions(java.util.List<Condition> conditions) {
  51. this.conditions = conditions;
  52. }
  53. public java.util.List<Order> getOrders() {
  54. return orders;
  55. }
  56. public void setOrders(java.util.List<Order> orders) {
  57. this.orders = orders;
  58. }
  59. public int getRecordCount() {
  60. return recordCount;
  61. }
  62. public void setRecordCount(int recordCount) {
  63. this.recordCount = recordCount;
  64. }
  65. public int getPageCount() {
  66. return pageCount;
  67. }
  68. public void setPageCount(int pageCount) {
  69. this.pageCount = pageCount;
  70. }
  71. public java.util.List<T> getResult() {
  72. return result;
  73. }
  74. public void setResult(java.util.List<T> result) {
  75. this.result = result;
  76. }
  77. public PageInfo(Class<T> classzz, int pageSize, int pageIndex,
  78. List<Condition> conditions, List<Order> orders) {
  79. super();
  80. this.classzz = classzz;
  81. this.pageSize = pageSize;
  82. this.pageIndex = pageIndex;
  83. this.conditions = conditions;
  84. this.orders = orders;
  85. }
  86. public PageInfo(Class<T> classzz) {
  87. super();
  88. this.classzz = classzz;
  89. }
  90. }


分页信息类中涉及的其它类:

筛选条件类:

  1. package org.accp.mhouse.pager;
  2. import java.io.Serializable;
  3. /**筛选条件类*/
  4. public class Condition implements Serializable {
  5. private String propertyName;
  6. private Compare cp = Compare.EQ;
  7. private Object propertyValue;
  8. public String getPropertyName() {
  9. return propertyName;
  10. }
  11. public void setPropertyName(String propertyName) {
  12. this.propertyName = propertyName;
  13. }
  14. public Compare getCp() {
  15. return cp;
  16. }
  17. public void setCp(Compare cp) {
  18. this.cp = cp;
  19. }
  20. public Object getPropertyValue() {
  21. return propertyValue;
  22. }
  23. public void setPropertyValue(Object propertyValue) {
  24. this.propertyValue = propertyValue;
  25. }
  26. public Condition(String propertyName, Compare cp, Object propertyValue) {
  27. super();
  28. this.propertyName = propertyName;
  29. this.cp = cp;
  30. this.propertyValue = propertyValue;
  31. }
  32. public Condition() {
  33. super();
  34. }
  35. }


多表连接抓取策略类:

  1. package org.accp.mhouse.pager;
  2. import java.io.Serializable;
  3. /**多表连接抓取策略类*/
  4. public class Fetch implements Serializable {
  5. /**属性名*/
  6. private String fetchPropertyName;
  7. /**别名*/
  8. private String aliasName;
  9. /**抓取方式*/
  10. private FetchMode fetchMode = FetchMode.INNER_JOIN;
  11. public FetchMode getFetchMode() {
  12. return fetchMode;
  13. }
  14. public void setFetchMode(FetchMode fetchMode) {
  15. this.fetchMode = fetchMode;
  16. }
  17. public String getFetchPropertyName() {
  18. return fetchPropertyName;
  19. }
  20. public void setFetchPropertyName(String fetchPropertyName) {
  21. this.fetchPropertyName = fetchPropertyName;
  22. }
  23. public String getAliasName() {
  24. return aliasName;
  25. }
  26. public void setAliasName(String aliasName) {
  27. this.aliasName = aliasName;
  28. }
  29. public Fetch(String fetchPropertyName, String aliasName) {
  30. super();
  31. this.fetchPropertyName = fetchPropertyName;
  32. this.aliasName = aliasName;
  33. }
  34. public Fetch() {
  35. super();
  36. }
  37. public Fetch(String fetchPropertyName, String aliasName, FetchMode fetchMode) {
  38. super();
  39. this.fetchPropertyName = fetchPropertyName;
  40. this.aliasName = aliasName;
  41. this.fetchMode = fetchMode;
  42. }
  43. }


排序类:

  1. package org.accp.mhouse.pager;
  2. import java.io.Serializable;
  3. /**排序*/
  4. public class Order implements Serializable {
  5. private String propertyName;
  6. private Direct direct = Direct.ASC;
  7. public String getPropertyName() {
  8. return propertyName;
  9. }
  10. public void setPropertyName(String propertyName) {
  11. this.propertyName = propertyName;
  12. }
  13. public Direct getDirect() {
  14. return direct;
  15. }
  16. public void setDirect(Direct direct) {
  17. this.direct = direct;
  18. }
  19. public Order(String propertyName, Direct direct) {
  20. super();
  21. this.propertyName = propertyName;
  22. this.direct = direct;
  23. }
  24. public Order() {
  25. super();
  26. }
  27. public Order(String propertyName) {
  28. super();
  29. this.propertyName = propertyName;
  30. }
  31. }


以上类中用到的一些枚举类型:

条件比较操作枚举:

  1. package org.accp.mhouse.pager;
  2. /**条件比较操作符【时间关系没有封装完】*/
  3. public enum Compare {
  4. EQ,
  5. GT,
  6. LT,
  7. GE,
  8. LE,
  9. NE,
  10. LIKE
  11. }


排序方式:

  1. package org.accp.mhouse.pager;
  2. /**排序方式*/
  3. public enum Direct {
  4. ASC,
  5. DESC
  6. }


抓取模式枚举:

  1. package org.accp.mhouse.pager;
  2. /**抓取模式*/
  3. public enum FetchMode {
  4. /**内连接*/
  5. INNER_JOIN,
  6. /**左外连接*/
  7. LEFT_JOIN
  8. }


分页重点实现代码:

  1. package org.accp.mhouse.dao.hbimpl;
  2. import java.io.Serializable;
  3. import java.util.List;
  4. import org.accp.mhouse.dao.HibernateSessionFactory;
  5. import org.accp.mhouse.dao.IHibernateCallback;
  6. import org.accp.mhouse.pager.Condition;
  7. import org.accp.mhouse.pager.Direct;
  8. import org.accp.mhouse.pager.Fetch;
  9. import org.accp.mhouse.pager.Order;
  10. import org.accp.mhouse.pager.PageInfo;
  11. import org.hibernate.Criteria;
  12. import org.hibernate.FetchMode;
  13. import org.hibernate.Session;
  14. import org.hibernate.Transaction;
  15. import org.hibernate.criterion.CriteriaSpecification;
  16. import org.hibernate.criterion.MatchMode;
  17. import org.hibernate.criterion.Projection;
  18. import org.hibernate.criterion.ProjectionList;
  19. import org.hibernate.criterion.Projections;
  20. import org.hibernate.criterion.Restrictions;
  21. import org.hibernate.transform.ResultTransformer;
  22. @SuppressWarnings("unchecked")
  23. public class CommonDao<T extends Serializable> {
  24. private Class<T> classzz;
  25. public CommonDao() {
  26. // TODO Auto-generated constructor stub
  27. }
  28. public CommonDao(Class<T> classzz) {
  29. // TODO Auto-generated constructor stub
  30. this.classzz = classzz;
  31. }
  32. /**分页方法*/
  33. public void pager(final PageInfo pi){
  34. if (pi==null || pi.getClasszz()==null){
  35. throw new RuntimeException("分页基本条件不全");
  36. }
  37. execute(new IHibernateCallback() {
  38. @Override
  39. public Object doInHibernate(Session session) {
  40. Criteria qbc = session.createCriteria(pi.getClasszz());
  41. //0.处理抓取策略
  42. prepareFetch(qbc,pi.getFetchs());
  43. //1.设置条件
  44. List<Condition> list = pi.getConditions();
  45. prepareCondition(qbc,list.toArray(new Condition[]{}));
  46. //2.计算总条数
  47. qbc.setProjection(Projections.rowCount());
  48. pi.setRecordCount(
  49. (Integer)qbc.uniqueResult()
  50. );
  51. //3.总页数
  52. pi.setPageCount(
  53. pi.getRecordCount()%pi.getPageSize()==0?
  54. pi.getRecordCount()/pi.getPageSize():
  55. pi.getRecordCount()/pi.getPageSize()+1
  56. );
  57. //4.清空投影查询的设置
  58. qbc.setProjection(null);
  59. qbc.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
  60. //5.处理排序
  61. prepareOrder(qbc,((List<Order>)pi.getOrders()).toArray(new Order[]{}));
  62. //6.获得分页结果
  63. pi.setResult(
  64. qbc
  65. .setFirstResult((pi.getPageIndex()-1)*pi.getPageSize())
  66. .setMaxResults(pi.getPageSize())
  67. .list()
  68. );
  69. return null;
  70. }
  71. });
  72. }
  73. /**处理分页条件*/
  74. private void prepareCondition(Criteria qbc,Condition...conditions){
  75. if (conditions==null || conditions.length==0)
  76. return;
  77. for (Condition cdt : conditions) {
  78. switch (cdt.getCp()) {
  79. case EQ:
  80. qbc.add(Restrictions.eq(cdt.getPropertyName(), cdt.getPropertyValue()));
  81. break;
  82. case GT:
  83. qbc.add(Restrictions.gt(cdt.getPropertyName(), cdt.getPropertyValue()));
  84. break;
  85. case LT:
  86. qbc.add(Restrictions.lt(cdt.getPropertyName(), cdt.getPropertyValue()));
  87. break;
  88. case GE:
  89. qbc.add(Restrictions.ge(cdt.getPropertyName(), cdt.getPropertyValue()));
  90. break;
  91. case LE:
  92. qbc.add(Restrictions.le(cdt.getPropertyName(), cdt.getPropertyValue()));
  93. break;
  94. case LIKE:
  95. qbc.add(Restrictions.like(cdt.getPropertyName(), cdt.getPropertyValue().toString(), MatchMode.ANYWHERE));
  96. break;
  97. default:
  98. break;
  99. }
  100. }
  101. }
  102. /**处理排序*/
  103. private void prepareOrder(Criteria qbc,Order...orders){
  104. if (orders==null || orders.length==0)
  105. return;
  106. for (Order ord : orders) {
  107. qbc.addOrder(
  108. ord.getDirect()==Direct.ASC?
  109. org.hibernate.criterion.Order.asc(ord.getPropertyName()):
  110. org.hibernate.criterion.Order.desc(ord.getPropertyName())
  111. );
  112. }
  113. }
  114. /**处理抓取策略*/
  115. private void prepareFetch(Criteria qbc,java.util.List<Fetch> fetchList){
  116. if (fetchList==null)
  117. return;
  118. for (Fetch fetch : fetchList) {
  119. if (null!=fetch.getAliasName() && !"".equals(fetch.getAliasName())){
  120. qbc.createAlias(
  121. fetch.getFetchPropertyName(),
  122. fetch.getAliasName(),
  123. fetch.getFetchMode()==org.accp.mhouse.pager.FetchMode.INNER_JOIN?CriteriaSpecification.INNER_JOIN:CriteriaSpecification.LEFT_JOIN
  124. );
  125. }
  126. }
  127. }
  128. /**通过回调执行任何Hibernate操作*/
  129. public Object execute(IHibernateCallback hibernateCallback){
  130. Session session = null;
  131. Transaction ts = null;
  132. Object result = null;
  133. try {
  134. session = HibernateSessionFactory.getSession();
  135. ts = session.beginTransaction();
  136. if (hibernateCallback!=null)
  137. result = hibernateCallback.doInHibernate(session);
  138. ts.commit();
  139. } catch(Exception e){
  140. ts.rollback();
  141. throw new RuntimeException(e.getMessage());
  142. } finally {
  143. if (session!=null) session.close();
  144. }
  145. return result;
  146. }
  147. /**多条件查询*/
  148. public List<T> findByProperties(Condition...conditions){
  149. if (conditions==null || conditions.length==0){
  150. return findAll();
  151. }
  152. Session session = null;
  153. try {
  154. session = HibernateSessionFactory.getSession();
  155. Criteria qbc = session.createCriteria(classzz);
  156. prepareCondition(qbc,conditions);
  157. return qbc.list();
  158. } catch (Exception e) {
  159. throw new RuntimeException(e.getMessage());
  160. } finally {
  161. if (session!=null) session.close();
  162. }
  163. }
  164. }


 测试代码:

  1. public static void main(String[] args) {
  2. CommonDao<House> cdao = new CommonDao<House>();
  3. PageInfo<House> pi = new PageInfo<House>(House.class);
  4. pi.getFetchs().add(new Fetch("street", "st"));
  5. pi.getFetchs().add(new Fetch("st.district","d"));
  6. pi.getFetchs().add(new Fetch("users","u"));
  7. pi.getFetchs().add(new Fetch("type","t"));
  8. pi.getConditions().add(new Condition("d.name", Compare.EQ, "青羊区"));
  9. pi.getOrders().add(new Order("id", Direct.ASC));
  10. cdao.pager(pi);
  11. System.out.printf("共%d条 %d页 当前第%d页\n",pi.getRecordCount(),pi.getPageCount(),pi.getPageIndex());
  12. for (House h : pi.getResult()) {
  13. System.out.println(h.getTitle()+"\t\t"+
  14. h.getStreet().getName()+"\t\t"+
  15. h.getStreet().getDistrict().getName()+"\t\t"+
  16. h.getUsers().getName()+"\t\t"+
  17. h.getType().getName()
  18. );
  19. }
  20. }


控制台输出:

  1. Hibernate:
  2. select
  3. count(*) as y0_
  4. from
  5. house.house this_
  6. inner join
  7. house.street st1_
  8. on this_.street_id=st1_.ID
  9. inner join
  10. house.district d2_
  11. on st1_.district_id=d2_.ID
  12. inner join
  13. house.type t4_
  14. on this_.type_id=t4_.ID
  15. inner join
  16. house.users u3_
  17. on this_.user_id=u3_.id
  18. where
  19. d2_.name=?
  20. Hibernate:
  21. select
  22. this_.ID as ID2_4_,
  23. this_.contact as contact2_4_,
  24. this_.description as descript3_2_4_,
  25. this_.floorage as floorage2_4_,
  26. this_.price as price2_4_,
  27. this_.pubdate as pubdate2_4_,
  28. this_.street_id as street8_2_4_,
  29. this_.title as title2_4_,
  30. this_.type_id as type9_2_4_,
  31. this_.user_id as user10_2_4_,
  32. st1_.ID as ID1_0_,
  33. st1_.district_id as district3_1_0_,
  34. st1_.name as name1_0_,
  35. d2_.ID as ID4_1_,
  36. d2_.name as name4_1_,
  37. t4_.ID as ID3_2_,
  38. t4_.name as name3_2_,
  39. u3_.id as id0_3_,
  40. u3_.idAdmin as idAdmin0_3_,
  41. u3_.name as name0_3_,
  42. u3_.password as password0_3_,
  43. u3_.telephone as telephone0_3_,
  44. u3_.userName as userName0_3_
  45. from
  46. house.house this_
  47. inner join
  48. house.street st1_
  49. on this_.street_id=st1_.ID
  50. inner join
  51. house.district d2_
  52. on st1_.district_id=d2_.ID
  53. inner join
  54. house.type t4_
  55. on this_.type_id=t4_.ID
  56. inner join
  57. house.users u3_
  58. on this_.user_id=u3_.id
  59. where
  60. d2_.name=?
  61. order by
  62. this_.ID asc limit ?
  63. 61页 当前第1
  64. 第一个房子 东南路 青羊区 admin 一室一厅
  65. 第七间房 东南路 青羊区 luo 两室一厅
  66. wrwegrhtrhgh 东南路 青羊区 admin 四室一厅
  67. gfdgggggggggggggg 东南路 青羊区 admin 两室一厅
  68. dfegggg 东南路 青羊区 admin 两室一厅
  69. rrrrr 知春路 青羊区 zhang 两室一厅
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/凡人多烦事01/article/detail/529029
推荐阅读
相关标签
  

闽ICP备14008679号