分享

Spring JPA 查询的几种方式并处理分页

 寂灭太极 2015-03-20

第一种 NamedQuery(返回方式为列模式[原生态sql的复杂查询])

1)dao层处理查询并分页

Java代码  收藏代码
  1. @SuppressWarnings("unchecked")  
  2.     public PageResult<T> getList(Integer currentPage){  
  3.         PageResult<T> pageResult = new PageResult<T>();  
  4.             int pageSize = Constant.DEFAULT_PAGE_SIZE;  
  5.             int start = (currentPage - 1) * pageSize;  
  6.             Query query = getEntityManager().createNamedQuery("ReturnTrainAppyUser");  
  7.             int total = query.getResultList().size();  
  8.             // 判断分页  
  9.             if (start < total && pageSize > 0) {  
  10.                 query.setFirstResult(start);  
  11.                 query.setMaxResults(pageSize);  
  12.                 pageResult.setFirst(start);  
  13.                 pageResult.setPageSize(pageSize);  
  14.             }  
  15.               
  16.             pageResult.setTotalCount(total);  
  17.             pageResult.setPageResultList(query.getResultList());  
  18.         return pageResult;  
  19.     }  

 2)控制层代码

Java代码  收藏代码
  1. @RequestMapping("/applyList")  
  2.     public String applyList(HttpServletRequest request,  
  3.             HttpServletResponse response, Model model) throws Exception {  
  4.         Integer currentPage = 1;  
  5.         Integer pageNum = getIntParameter(request, "pageNum");  
  6.         if (pageNum != null) {  
  7.             currentPage = getIntParameter(request, "pageNum");  
  8.         }  
  9.         PageResult<TrainApply> a = trainApplyService.findContentResult(currentPage);  
  10.         addPageResultModel2(a, currentPage, model);  
  11.         return "common/train/admin/applyList";  
  12.     }  

  处理分页参数

 

Java代码  收藏代码
  1. protected <E extends VO> void addPageResultModel2(PageResult<E> pct,Integer currentPage, Model model) {  
  2.     model.addAttribute("totalCount", pct.getTotalCount());  
  3.     model.addAttribute("numPerPage", Constant.DEFAULT_PAGE_SIZE);  
  4.     model.addAttribute("pageNum", currentPage);  
  5.     model.addAttribute("pageNumShown", pct.getPageCount(pct.getTotalCount(), Constant.DEFAULT_PAGE_SIZE));  
  6.     model.addAttribute("currentPage", currentPage);  
  7.     model.addAttribute("itemList", pct.getPageResultList());  
  8. }  

 3)实体类

Java代码  收藏代码
  1. @NamedNativeQueries  
  2. (  
  3.     {  
  4.        @NamedNativeQuery(  
  5.            name="ReturnTrainAppyUser",  
  6.            query=" select a.id as apply_id,b.id as plan_id,b.title as plan_title,(select count(c.id) from train_apply_user c where c.APPLY_ID=a.ID) as 'apply_user_num',a.company as 'apply_company' from train_apply a inner join train_plan b on b.ID=a.PLAN_ID",  
  7.            resultSetMapping="ReturnTrainAppyUser"),  
  8. }  
  9. )  
  10. @SqlResultSetMappings(  
  11. {  
  12.     @SqlResultSetMapping  
  13.     (  
  14.        name="ReturnTrainAppyUser",  
  15.        entities={},  
  16.        columns=  
  17.        {  
  18.            @ColumnResult(name="apply_id"),  
  19.            @ColumnResult(name="plan_id"),  
  20.            @ColumnResult(name="plan_title"),  
  21.            @ColumnResult(name="apply_user_num"),  
  22.            @ColumnResult(name="apply_company")  
  23.        }  
  24.     )  
  25. })  
  26. @Entity  
  27. @Table(name = "train_apply")  
  28. public class TrainApply extends VO {  
  29.     private static final long serialVersionUID = -6530604520661376764L;  
  30.     @Id  
  31.     @GeneratedValue(strategy = GenerationType.IDENTITY)  
  32.     private Long id;// ID  
  33.     private Long planId;//计划ID  
  34.     private String orgName;//单位名称  
  35.     private String roomType;//客房类型  
  36.     private String roomNumber;//客房数  
  37.     private String invoiceType;//发票类型  
  38.     private String status;//状态  
  39.       
  40.       
  41.       
  42.     public Long getId() {  
  43.         return id;  
  44.     }  
  45.     public void setId(Long id) {  
  46.         this.id = id;  
  47.     }  
  48.     public Long getPlanId() {  
  49.         return planId;  
  50.     }  
  51.     public void setPlanId(Long planId) {  
  52.         this.planId = planId;  
  53.     }  
  54.     public String getOrgName() {  
  55.         return orgName;  
  56.     }  
  57.     public void setOrgName(String orgName) {  
  58.         this.orgName = orgName;  
  59.     }  
  60.     public String getRoomType() {  
  61.         return roomType;  
  62.     }  
  63.     public void setRoomType(String roomType) {  
  64.         this.roomType = roomType;  
  65.     }  
  66.     public String getRoomNumber() {  
  67.         return roomNumber;  
  68.     }  
  69.     public void setRoomNumber(String roomNumber) {  
  70.         this.roomNumber = roomNumber;  
  71.     }  
  72.     public String getInvoiceType() {  
  73.         return invoiceType;  
  74.     }  
  75.     public void setInvoiceType(String invoiceType) {  
  76.         this.invoiceType = invoiceType;  
  77.     }  
  78.     public String getStatus() {  
  79.         return status;  
  80.     }  
  81.     public void setStatus(String status) {  
  82.         this.status = status;  
  83.     }  
  84.       
  85. }  

 4)页面处理

Java代码  收藏代码
  1. <table width="100%" cellspacing="0" cellpadding="0">  
  2.             <thead>  
  3.                 <tr class="Train_Resultlist-item">  
  4.                     <th width="50">NO.</th>  
  5.                     <th>培训计划</th>  
  6.                     <th>报名人数</th>  
  7.                     <th>操作</th>  
  8.                 </tr>  
  9.             </thead>  
  10.             <tbody>  
  11.                 <c:forEach var="item" items="${itemList}" varStatus="s">  
  12.                 <tr>  
  13.                     <td>${s.index + 1}</td>  
  14.                     <td>${item[2]}</td>  
  15.                     <td>${item[3]}</td>  
  16.                     <td>  
  17.                     <div  class="applylist_operate">  
  18.                         <a class="icon icon_train_edit" href="<c:url value='/train/admin/applyEdit/${item[0]}.htm'/>"></a>  
  19.                         <a class="icon icon_train_delete" href="<c:url value='/train/admin/applyDelete'/>/${item[0]}.htm"  title="确定要删除吗?删除后数据将不可恢复"></a>  
  20.                     </div>      
  21.                     </td>  
  22.                 </tr>  
  23.                 </c:forEach>  
  24.                 <!-- 分页start -->  
  25.                 <tr>  
  26.                     <td colspan="4">  
  27.                             <div class="green-black">  
  28.                                 共${totalCount}条数据.  
  29.                                 <a title="首页" href="<c:url value='/train/admin/applyList.htm?pageNum=1'/>">首页</a>   
  30.                                 <c:if test="${currentPage le 1}" var="syy">  
  31.                                 <a title="上一页" href="#">上一页</a>  
  32.                                 </c:if>  
  33.                                 <c:if test="${!syy}">  
  34.                                 <a title="上一页" href="<c:url value='/train/admin/applyList.htm?pageNum=${currentPage-1}'/>">上一页</a>  
  35.                                 </c:if>  
  36.                                 <c:forEach var="pageNo" begin="1" end="${pageNumShown}">  
  37.                                         <a href="<c:url value='/train/admin/applyList.htm?pageNum=${pageNo}'/>">  
  38.                                         <c:if test="${currentPage eq pageNo}" var="rsFy">  
  39.                                             <strong>${pageNo}</strong>  
  40.                                         </c:if>  
  41.                                         <c:if test="${!rsFy}">  
  42.                                             ${pageNo}  
  43.                                         </c:if>  
  44.                                         </a>  
  45.                                 </c:forEach>  
  46.                                 <c:if test="${currentPage ge pageNumShown}" var="xyy">  
  47.                                     <a title="下一页" href="#">下一页</a>  
  48.                                 </c:if>  
  49.                                 <c:if test="${!xyy}">  
  50.                                     <a title="下一页" href="<c:url value='/train/admin/applyList.htm?pageNum=${currentPage+1}'/>">下一页</a>  
  51.                                 </c:if>  
  52.                                 <a title="尾页" href="<c:url value='/train/admin/applyList.htm?pageNum=${pageNumShown}'/>">尾页</a>  
  53.                             </div>  
  54.                     </td>  
  55.                 </tr>  
  56.                 <!-- 分页end -->                              
  57.             </tbody>  
  58.         </table>  

 

 

第二种createNativeQuery(返回方式为实体对象集合)

1)dao层代码

Java代码  收藏代码
  1. @SuppressWarnings("unchecked")  
  2.     public PageResult<T> getList(Integer currentPage){  
  3.         int pageSize = Constant.DEFAULT_PAGE_SIZE;  
  4.         int start = (currentPage - 1) * pageSize;  
  5.         String sql="select a.* "  
  6.                 +" from train_apply a inner join train_plan b on b.ID=a.PLAN_ID";  
  7.         PageResult<T> pageResult = new PageResult<T>();  
  8.           
  9.         Query query = getEntityManager().createNativeQuery(sql.toString(),TrainApply.class);  
  10.         int total = query.getResultList().size();  
  11.         // 判断分页  
  12.         if (start < total && pageSize > 0) {  
  13.             query.setFirstResult(start);  
  14.             query.setMaxResults(pageSize);  
  15.             pageResult.setFirst(start);  
  16.             pageResult.setPageSize(pageSize);  
  17.         }  
  18.         pageResult.setTotalCount(total);  
  19.         pageResult.setPageResultList(query.getResultList());  
  20.         return pageResult;  
  21.     }  

 2)其他与第一种类似,实体类不需要注释@NamedNativeQueries等。页面读取为item.planId类似方法获取数据,而不是item[0],item[1]。。。只是对于复杂的sql好像不太适合,比如说要count(id)某一列,目前用这种方式还不能实现几个表直接复杂字段展现查询。待研究。

 

 

第三种 注解对象查询(返回方式为实体对象集合)

1)dao层

Java代码  收藏代码
  1. @Query("select new TrainApplyVo(a.id,count(c.id) as applyUserNum,a.orgName as applyUserCompany)"  
  2.             +" from TrainApply a,TrainPlan b,TrainApplyUser c where b.id=a.planId and a.id=c.applyId and b.id = ?1 group by b.id")  
  3.     public List<TrainApply> getTrainApplyListByPlanId(Long planId);  

 2)这里可查询集合,但是暂时还没有方法如何去处理分页。。。

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约