java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > kkpaper分页组件

Spring MVC结合Spring Data JPA实现按条件查询和分页

作者:王晓东1号

这篇文章主要为大家详细介绍了Spring MVC结合Spring Data JPA实现按条件查询,以及分页效果,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文实例为大家分享了Android九宫格图片展示的具体代码,供大家参考,具体内容如下

推荐视频:尚硅谷Spring Data JPA视频教程,一学就会,百度一下就有。

后台代码:在DAO层继承Spring Data JPA的PagingAndSortingRepository接口实现的 (实现方法主要在SbglServiceImpl.java类中)

前台表现:用kkpaper表现出来

实现效果:

1、实体类

package com.jinhetech.yogurt.sbgl.entity;

import java.io.Serializable;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;

import org.hibernate.annotations.GenericGenerator;
import org.springframework.cache.annotation.Cacheable;
@Entity
@Table(name="SYS_SBGL")
@PrimaryKeyJoinColumn(name = "SBBM")
@Cacheable(value = "baseCache")
public class Sbgl implements Serializable{


  private static final long serialVersionUID = -1423899016746755470L;

  @Id
  private String sbbm;
  
  private String sbmc;
  private String sblx;
  private String sssx;
  private String ssjd;
  
  private String azsj;
  private String azry;
  private String sbzt;
  private String sbjd;
  private String sbwd;
  
  private String wxlxr;
  private String wxlxdh;
  private String sbywxcs;
  private String jzpylyz;
  private String mqsbcyr;
  private String bzsm;
  
    
  //setter、getter方法省略
  
}

2、jsp页面,看最下面的分页组件(kkpaper)

resultMap集合是下面Controller中最后查询和分页后获得的所有数据信息,resultMap.resultList:resultList是Map集合的属性,里面存着<key,value>数据

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core_rt" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
<!doctype html>

<c:set var="ctx" value="${pageContext.request.contextPath}" scope="session"/>

<html>
<head>
  <title>设备管理</title>
  <!-- zTree需要的样式和js -->
  <link rel="stylesheet" href="${ctx }/yogurtResource/assembly/ztree/css/zTreeStyle.css" rel="external nofollow" type="text/css">
  <script type="text/javascript" src="${ctx }/yogurtResource/assembly/ztree/jquery.ztree.core-3.5.js"></script>
  <script type="text/javascript" src="${ctx }/yogurtResource/assembly/ztree/jquery.ztree.excheck-3.5.js"></script>
  
  <!-- 验证框架 -->
  <script type="text/javascript" src="${ctx }/yogurtResource/assembly/yogurt/user/formValidate.js"></script>
  
  <!-- 修改表单验证错误提示样式 -->
  <style type="text/css">
    .table-bordered-ul li{ margin:0 5px; float:left}
    label.error {
     padding-left: 16px;
    
     padding-bottom: 2px;
    
     font-weight: bold;
    
     color: #F00;
    }
  </style>
  
  <script type="text/javascript">
  function console(consoleTag, userId, stateTag) {
      // 添加用户。
    if("add" == consoleTag) {
      $('#formid').prop("action", "${ctx}/sbgl/sbgl_add_list");
    }
 
  }
        
  /**
   * 搜索。
   */
  function search() {
    $('#searchForm').submit();
  }      
  
  </script>
  
</head>

<body>
  <div class="clear">
    <div class="panel panel-default yogurt_route" id="yogurt_route">
      <a href="${ctx }/home/home_list" rel="external nofollow" >首页</a> > <a
        href="javascript:void(0);" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" onclick="navigate();">设备管理</a> > 设备列表
    </div>
  </div>
  
  <ul id="bqnum">
    <li><a href="javascript:void(0);" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" onclick="navigate();">导航</a>
    </li>
    <li><a href="javascript:void(0);" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" onclick="orgTree();">机构</a>
    </li>
  </ul>
  
  <!-- 根据条件查询 -->
  <div class="clear ppd10" style="line-height:32px">
    <form action="${ctx }/sbgl/sbgl_list" method="post" id="searchForm">
      <div style="float:left; width:200px">
        设备名称:
        <input type="text" name="serSbmc" id="serSbmc" >
      </div>
      <div class="floatleft">
        &nbsp;&nbsp;设备类型:
        <input type="text" name="serSblx" id="serSblx" >
      </div>
      <div class="floatleft">
        &nbsp;&nbsp;所属市县:
        <input type="text" name="serSssx" id="serSssx" >
      </div>
      <div class="floatleft">
        &nbsp;&nbsp;基地名称:
        <input type="text" name="serJdmc" id="serJdmc" >
      </div>
      <div class="floatleft">
        &nbsp;&nbsp;设备状态:
        <select class="form-control" style="display:inline-block; width:80px" name="serSbzt" id="serSbzt">
          <option value="">全部</option>
          <option value="Y">正常</option>
          <option value="N">异常</option>
        </select>
      </div>&nbsp;&nbsp;&nbsp;&nbsp;
      <button type="submit" class="btn btn-success yogurt_search_button" onclick="search();">
        <img src="${ctx }/yogurtResource/images/Panel/search.png" width="18" height="18" />
      </button>
    </form>
  </div>
  
  <!-- 新增、删除 -->
  <div class="panel panel-default" style="margin-top:10px">
    <div class="yogurt_panel_title_core">
      <span class="state_bold">共查询出数据结果:<span class="state_red">${resultMap.totalNum}</span>条</span>
    </div>
    <div class="more_core3">
      <!-- <button type="button" class="btn btn-success yogurt_search_button2" onclick="console('add','');">新增设备</button> -->
      <button type="button" class="btn btn-success yogurt_search_button2" onclick="window.location.href='${ctx }/sbgl/sbgl_add_list' ">新增设备</button>
      <button type="button" class="btn btn-success yogurt_search_button2" onclick="console('delete','');">删除设备</button>
    </div>
  </div>
  <!-- 列表 -->
  <div class="yogurt_elementsbox_core clear">
    <div class="yogurt_elementsbox_table_article" id="yogurt_elementsbox_table_article">
      <table id="tableBody" border="0" cellspacing="0" cellpadding="0" class="table yogurt_elementsbox_table">
        <thead>
          <tr class="yogurt_tab_back" onmouseover="this.className='yogurt_tab_trhover'" onmouseout="this.className='yogurt_tab_back'">
            <th width="3%"><input type="checkbox" onClick="allchecked(this)"></th>
            <th width="10%">设备名称</th>
            <th width="10%">设备类型</th>
            <th width="10%">所属市县</th>
            <th width="10%">基地名称</th>
            <th width="10%">设备状态</th>
            <th width="10%">维修联系人</th>
            <th width="10%">联系电话</th>
            <th width="10%">设备持有人</th>
            <th width="17%" style="text-align:center;">操作</th>
          </tr>
        </thead>
        <tbody id="userTb">
          <c:forEach var="sbgl" items="${resultMap.resultList}" varStatus="status">
            <tr>
              <td><input type="checkbox" ></td>
              <td>${sbgl.sbmc }</td>
              <td>${sbgl.sblx }</td>
              <td>${sbgl.sssx }</td>
              <td>${sbgl.ssjd }</td>
              <td>${sbgl.sbzt }</td>
              <td>${sbgl.wxlxr }</td>
              <td>${sbgl.wxlxdh }</td>
              <td>${sbgl.mqsbcyr }</td>
              <td style="text-align:center">
                <a href="javascript:void(0);" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" onclick="console('update', '${user.userId}')"> 修改</a>
                <a href="javascript:void(0);" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" onclick="showRoles('${user.userId}')">| 查看</a>
              </td>
            </tr>
          </c:forEach>
        </tbody>
      
      </table>
      
      
    </div>
  </div>
  
  
    <!--分页-->
  <div style="clear:both; height:50px">
    <!--加载分页组件-->
    <div id="kkpager"></div>
    <script type="text/javascript">
      var param = "";

      $(function() {
        var totalPage = "${resultMap.totalPage}";
        var totalRecords = "${resultMap.totalNum}";
        var pageSize = "${resultMap.pageSize}";

        var pageNum = parseInt("${resultMap.pageNum}") + 1;
        //初始化分页控件
        //有些参数是可选的,比如lang,若不传有默认值
        kkpager.init({
          pno: pageNum,
          //总页码
          total: "${resultMap.totalPage}",
          //总数据条数
          totalRecords: totalRecords,
          //链接前部
          hrefFormer: 'sbgl_list',
          //链接尾部
          hrefLatter: '',
          getLink: function(n) {
            return getInitParam() + "&pageNum=" + n + "&pageSize=" + pageSize;
          },
          lang: {
            prePageText: '上一页',
            nextPageText: '下一页',
            totalPageBeforeText: '共',
            totalPageAfterText: '页',
            totalRecordsAfterText: '条数据',
            gopageBeforeText: '转到',
            gopageButtonOkText: '确定',
            gopageAfterText: '页',
            buttonTipBeforeText: '第',
            buttonTipAfterText: '页'
          }
        });
        //生成
        kkpager.generPageHtml();

        $('#mykkpagerselect').val(pageSize);
      });

      function returnoption(pageSize) {
        window.location.href = getInitParam() + "&pageNum=1&pageSize=" + pageSize;
      }

      function getInitParam() {
        var serSbmc = $('#serSbmc').val();
        var serSblx = $('#serSblx').val();
        var serSssx = $('#serSssx').val();
        var serJdmc = $('#serJdmc').val();
        var serSbzt = $('#serSbzt').val();

        var attr = "?serSbmc=" + encodeURI(encodeURI(serSbmc)) 
            + "&serSblx=" + serSblx + "&serSssx=" + serSssx + "&serJdmc=" + serJdmc+ "&serSbzt=" + serSbzt;
        return "${ctx}/sbgl/sbgl_list" + attr;
      }
    </script>
    <!--分页结束-->
  </div>
  <!--分页end-->
 
</body>
</html>

3、Controller(看红色字体下面那个处理方法)

package com.jinhetech.yogurt.sbgl.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.view.RedirectView;

import com.jinhetech.yogurt.dictionary.crop.service.impl.CropServiceImpl;
import com.jinhetech.yogurt.func.entity.Func;
import com.jinhetech.yogurt.func.service.FuncService;
import com.jinhetech.yogurt.menu.entity.Menu;
import com.jinhetech.yogurt.menu.service.MenuService;
import com.jinhetech.yogurt.menu.util.MenuUtil;
import com.jinhetech.yogurt.organization.entity.OrgTable;
import com.jinhetech.yogurt.organization.service.OrgService;
import com.jinhetech.yogurt.organization.util.OrgUtil;
import com.jinhetech.yogurt.role.entity.Role;
import com.jinhetech.yogurt.role.service.RoleService;
import com.jinhetech.yogurt.sbgl.dao.SbglDao;
import com.jinhetech.yogurt.sbgl.entity.Sbgl;
import com.jinhetech.yogurt.sbgl.service.SbglService;
import com.jinhetech.yogurt.sbgl.util.SbglUtil;
import com.jinhetech.yogurt.user.entity.User;
import com.jinhetech.yogurt.user.entity.UserInfo;
import com.jinhetech.yogurt.user.service.UserService;
import com.jinhetech.yogurt.user.util.UserUtil;
import com.jinhetech.yogurt.util.base.BaseController;
import com.jinhetech.yogurt.util.base.Constants;
import com.jinhetech.yogurt.util.common.TextUtils;
import com.jinhetech.yogurt.util.common.UUIDHexGenerator;

/**
 * 系统用户管理控制类
 * 
 * @author Wang Hao
 * @version 1.0 2014-02-28 初版
 */
@Controller("sbglController")
@RequestMapping("/sbgl")
public class SbglController extends BaseController {
//  @Resource(name = "sbglDao")
//  private SbglDao sbglDao;
  
  @Resource(name = "sbglService")
  private SbglService sbglService;
  
  /**
   * 平台权限管理导航*/
  @RequestMapping("/home_list")
  public ModelAndView home() {

    return new ModelAndView("iot/permis/permis_home");
  }
  
  
  /**
   * 查询设备信息列表(支持分页和多条件查询)。
   * 
   */
  @RequestMapping("sbgl_list")
  @RequiresRoles("sbgl/sbgl_list")
  public String getUserList(Model model) throws Exception {
    //显示设备列表
//    List<Sbgl> lst=new ArrayList<Sbgl>();
//    lst=(List<Sbgl>) sbglService.getAll();
    
    Map<String, Object> resultMap = null;
    // 查询表单或分页保持请求时 请求参数的接收
    Map<String, String> serArgs = new HashMap<String, String>();
    serArgs = SbglUtil.getSelArgsToMap(request);//这个类在下面给出
    

    resultMap = sbglService.getUserBySearch(serArgs, "wxlxdh");
    
    model.addAttribute("resultMap", resultMap);
//    model.addAttribute("lst", lst);

    return "sbgl/sbgl_list";
  }

  /**
   * 新增设备信息列表(支持分页和多条件查询)。
   * 
   * @author YangZhenghua 2014-5-28
   * @throws Exception
   */
  @RequestMapping("sbgl_add_list")
  @RequiresRoles("sbgl/sbgl_add_list")
  public String getAddList(Model model) throws Exception {

    
    System.out.println("aaa");
    model.addAttribute("aaa","aaa");
    model.addAttribute("resultMap", "hello world");
    

    return "sbgl/sbgl_add_list";
  }
  
  
  /**
   * 保存、修改用户信息。
   * 
   * @author YangZhenghua 2014-5-28
   * @throws Exception
   */
  @RequestMapping("sbgl_save_list")
  @RequiresRoles("sbgl/sbgl_save_list")
  public ModelAndView SaveSbgl(Sbgl sbgl) throws Exception {

    String sbmc=request.getParameter("sbmc");
    String sblx=request.getParameter("sblx");
    String sssx=request.getParameter("sssx");
    String ssjd=request.getParameter("ssjd");
    String azsj=request.getParameter("azsj");
    
    String azry=request.getParameter("azry");
    String sbzt=request.getParameter("sbzt");
    String sbjd=request.getParameter("sbjd");
    String sbwd=request.getParameter("sbwd");
    String wxlxr=request.getParameter("wxlxr");
    
    String wxlxdh=request.getParameter("wxlxdh");
    String sbywxcs=request.getParameter("sbywxcs");
    String jzpylyz=request.getParameter("jzpylyz");
    String mqsbcyr=request.getParameter("mqsbcyr");
    String bzsm=request.getParameter("bzsm");
    
    sbgl.setSbbm(UUIDHexGenerator.generate());
    sbgl.setSbmc(sbmc);
    sbgl.setSblx(sblx);
    sbgl.setSssx(sssx);
    sbgl.setSsjd(ssjd);
    sbgl.setAzsj(azsj);
    
    sbgl.setAzry(azry);
    sbgl.setSbzt(sbzt);
    sbgl.setSbjd(sbjd);
    sbgl.setSbwd(sbwd);
    sbgl.setWxlxr(wxlxr);
    
    sbgl.setWxlxdh(wxlxdh);
    sbgl.setSbywxcs(sbywxcs);
    sbgl.setJzpylyz(jzpylyz);
    sbgl.setMqsbcyr(mqsbcyr);
    sbgl.setBzsm(bzsm);

    sbglService.save(sbgl);

    return new ModelAndView(new RedirectView("sbgl_list"));
  }


}

3.2、SbglUtil.java

封装从前台传递过来的查询参数、前台传递过来的分页参数,都放到Map集合serArgs中

package com.jinhetech.yogurt.sbgl.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.jinhetech.yogurt.organization.entity.OrgTable;
import com.jinhetech.yogurt.report.entity.Report;
import com.jinhetech.yogurt.role.entity.Role;
import com.jinhetech.yogurt.user.entity.User;
import com.jinhetech.yogurt.user.entity.UserInfo;
import com.jinhetech.yogurt.util.common.JSONUtils;
import com.jinhetech.yogurt.util.common.TextUtils;

/**
 * 用户功能模块工具类。
 * 
 * @author YangZhenghua
 * @version V1.0 2014-5-16 初版
 * 
 */
public class SbglUtil {

  /**
   * 封装从前台传递过来的查询参数。
   * 
   * @author YangZhenghua
   * @date 2014-6-26
   */
  public static Map<String, String> getSelArgsToMap(HttpServletRequest request) throws Exception {
    Map<String, String> serArgs = new HashMap<String, String>();

    String serSbmc = request.getParameter("serSbmc");
    String serSblx = request.getParameter("serSblx");
    String serSssx = request.getParameter("serSssx");
    String serJdmc = request.getParameter("serJdmc");
    String serSbzt = request.getParameter("serSbzt");
    
    String pageNum = request.getParameter("pageNum") == null ? "1" : request.getParameter("pageNum");
    String pageSize = request.getParameter("pageSize") == null ? "10" : request.getParameter("pageSize");


    //serArgs.put("serUserName", java.net.URLDecoder.decode(serUserName == null ? "" : serUserName, "UTF-8"));
    serArgs.put("serSbmc", serSbmc);
    serArgs.put("serSblx", serSblx);
    serArgs.put("serSssx", serSssx);
    serArgs.put("serJdmc", serJdmc);
    serArgs.put("serSbzt", serSbzt);
    
    serArgs.put("pageNum", pageNum);
    serArgs.put("pageSize", pageSize);

    return serArgs;
  }



}

3.3、SbglService.java

package com.jinhetech.yogurt.sbgl.service;

import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jinhetech.yogurt.sbgl.entity.Sbgl;


public interface SbglService {

  public List<Sbgl> getAll() throws Exception;
  
  public Sbgl save(Sbgl sbgl) throws Exception;
  
  public Map<String, Object> getUserBySearch(Map<String, String> serArgs, final String sortType) throws Exception;
  
}

3.4、SbglServiceImpl.java (根据前台传递来的查询参数进行查询,获得的结果数据放到Page objPage参数)

package com.jinhetech.yogurt.sbgl.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.ListJoin;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jinhetech.yogurt.role.entity.Role;
import com.jinhetech.yogurt.sbgl.dao.SbglDao;
import com.jinhetech.yogurt.sbgl.entity.Sbgl;
import com.jinhetech.yogurt.sbgl.service.SbglService;
import com.jinhetech.yogurt.user.entity.UserInfo;
import com.jinhetech.yogurt.util.common.PageUtils;
import com.jinhetech.yogurt.util.common.TextUtils;

@Service("sbglService")
@Transactional
public class SbglServiceImpl implements SbglService{

  @Resource(name = "sbglDao")
  private SbglDao sbglDao;
  
  
  public List<Sbgl> getAll() throws Exception{
    
    return (List<Sbgl>) this.sbglDao.findAll();
  }

  public Sbgl save(Sbgl sbgl) throws Exception {
    return sbglDao.save(sbgl);
  }
  
  
  /**
   * 查询用户信息列表(支持分页和多条件查询)。
   * 
   * @author YangZhenghua 2014-6-19
   */
  public Map<String, Object> getUserBySearch(final Map<String, String> serArgs, final String sortType) throws Exception {

    // 获得分页对象pageable,并且在pageable中页码是从0开始,设定按照sortType升序排列
    Pageable pageable = PageUtils.buildPageRequest(Integer.valueOf(serArgs.get("pageNum")),
        Integer.valueOf(serArgs.get("pageSize")), sortType);

    Page<Sbgl> objPage = sbglDao.findAll(new Specification<Sbgl>() {

      public Predicate toPredicate(Root<Sbgl> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
        List<Predicate> lstPredicates = new ArrayList<Predicate>();

        if (TextUtils.isNotBlank(serArgs.get("serSbmc"))) {
          lstPredicates.add(cb.like(root.get("sbmc").as(String.class), "%" + serArgs.get("serSbmc") + "%"));
        }
        if (TextUtils.isNotBlank(serArgs.get("serSblx"))) {
          lstPredicates.add(cb.like(root.get("sblx").as(String.class), "%" + serArgs.get("serSblx") + "%"));
        }
        if (TextUtils.isNotBlank(serArgs.get("serSssx"))) {
          lstPredicates.add(cb.like(root.get("sssx").as(String.class), "%" + serArgs.get("serSssx") + "%"));
        }
        if (TextUtils.isNotBlank(serArgs.get("serJdmc"))) {
          lstPredicates.add(cb.like(root.get("jdmc").as(String.class), "%" + serArgs.get("serJdmc") + "%"));
        }

        if (TextUtils.isNotBlank(serArgs.get("serSbzt"))) {
          lstPredicates.add(cb.equal(root.get("sbzt"), serArgs.get("serSbzt")));
        }

        Predicate[] arrayPredicates = new Predicate[lstPredicates.size()];
        return cb.and(lstPredicates.toArray(arrayPredicates));
      }
    }, pageable);

    return PageUtils.getPageMap(objPage);
  }
  
  
}

3.4.1、PageUtils.java(分页数据工具类)

package com.jinhetech.yogurt.util.common;

import java.util.HashMap;
import java.util.Map;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;

import com.jinhetech.yogurt.util.base.Constants;

/**
 * 分页数据工具类。
 * 
 * @author YangZhenghua
 * @version V1.0 2014-6-24 初版
 * 
 */
public class PageUtils {

  /**
   * 封装分页数据到Map中。
   */
  public static Map<String, Object> getPageMap(Page<?> objPage) {
    Map<String, Object> resultMap = new HashMap<String, Object>();

    resultMap.put(Constants.PAGE_RESULT_LIST, objPage.getContent()); // 数据集合
    resultMap.put(Constants.PAGE_TOTAL_NUM, objPage.getTotalElements()); // 总记录数
    resultMap.put(Constants.PAGE_TOTAL_PAGE, objPage.getTotalPages()); // 总页数
    resultMap.put(Constants.PAGE_NUM, objPage.getNumber()); // 当前页码
    resultMap.put(Constants.PAGE_SIZE, objPage.getSize()); // 每页显示数量

    return resultMap;
  }

  /**
   * 创建分页请求。
   * 
   * @author YangZhenghua
   * @date 2014-7-14
   * 
   * @param pageNum 当前页
   * @param pageSize 每页条数
   * @param sortType 排序字段
   * @param direction 排序方向
   */
  public static PageRequest buildPageRequest(int pageNum, int pageSize, String sortType, String direction) {
    Sort sort = null;

    if (!TextUtils.isNotBlank(sortType)) {
      return new PageRequest(pageNum - 1, pageSize);
    } else if (TextUtils.isNotBlank(direction)) {
      if (Direction.ASC.equals(direction)) {
        sort = new Sort(Direction.ASC, sortType);
      } else {
        sort = new Sort(Direction.DESC, sortType);
      }
      return new PageRequest(pageNum - 1, pageSize, sort);
    } else {
      sort = new Sort(Direction.ASC, sortType);
      return new PageRequest(pageNum - 1, pageSize, sort);
    }
  }

  /**
   * 创建分页请求(该方法可以放到util类中).
   */
  public static PageRequest buildPageRequest(int pageNum, int pageSize, String sortType) {
    return buildPageRequest(pageNum, pageSize, sortType, null);
  }
  
  /**
   * 创建分页请求
   * 
   * @author YangZhenghua
   * @date 2014-11-12
   * 
   * @param pageNum
   * @param pageSize
   * @param sort
   * @return
   */
  public static PageRequest buildPageRequest(int pageNum, int pageSize, Sort sort) {
    return new PageRequest(pageNum - 1, pageSize, sort);
  }

  /**
   * 创建分页请求(该方法可以放到util类中).
   */
  public static PageRequest buildPageRequest(int pageNum, int pageSize) {
    return buildPageRequest(pageNum, pageSize, null, null);
  }

}

 4、DAO(SbglDao.java),对,只需要继承Spring Data JPA的PagingAndSortingRepository接口,Controller中调用其findAll()方法

package com.jinhetech.yogurt.sbgl.dao;

import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Repository;

import com.jinhetech.yogurt.sbgl.entity.Sbgl;
import com.jinhetech.yogurt.user.entity.UserInfo;

@Repository("sbglDao")
public interface SbglDao extends PagingAndSortingRepository<Sbgl, String>, JpaSpecificationExecutor<Sbgl> {
  
  
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文