SpringData中的分頁功能如何留JPA+kkpager實現(xiàn)

Spring Data中的分頁功能如何留 JPA+kkpager實現(xiàn)?相信很多沒有經(jīng)驗的人對此束手無策,為此本文總結(jié)了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個問題。

創(chuàng)新互聯(lián)公司是一家專注于網(wǎng)站設(shè)計、網(wǎng)站建設(shè)與策劃設(shè)計,烏蘇網(wǎng)站建設(shè)哪家好?創(chuàng)新互聯(lián)公司做網(wǎng)站,專注于網(wǎng)站建設(shè)10年,網(wǎng)設(shè)計領(lǐng)域的專業(yè)建站公司;建站業(yè)務(wù)涵蓋:烏蘇等地區(qū)。烏蘇做網(wǎng)站價格咨詢:13518219792

一、spring Data JPA分頁

分頁效果如下:

Spring Data中的分頁功能如何留 JPA+kkpager實現(xiàn)

前臺表格用的是: Bootstrap

分頁插件用的是: kkpager

kkpager是一個js分頁展示控件,傳入簡單參數(shù)就能使用的分頁效果控件,github地址:https://github.com/pgkk/kkpager

項目結(jié)構(gòu):

Spring Data中的分頁功能如何留 JPA+kkpager實現(xiàn)

FamilyMember實體類:

package com.fendo.entity; 
 
import java.io.Serializable; 
import java.util.Date; 
 
import javax.persistence.Column; 
import javax.persistence.Entity; 
import javax.persistence.GeneratedValue; 
import javax.persistence.GenerationType; 
import javax.persistence.Id; 
import javax.persistence.Table; 
 
import org.hibernate.annotations.GenericGenerator; 
 
 
 
@Entity 
@Table(name="FAMILY_MEMBER") 
public class FamilyMember implements Serializable{ 
 
  private Integer id; 
  private String FamilyName; 
  private String FamilyCharge; 
  private String Mobile; 
  private String Email; 
  private String Address; 
  private Date CreateData; 
   
  @Id 
  @GeneratedValue(strategy=GenerationType.IDENTITY) 
  public Integer getId() { 
    return id; 
  } 
  public void setId(Integer id) { 
    this.id = id; 
  } 
   
   
  @Column(name="FAMILY_NAME") 
  public String getFamilyName() { 
    return FamilyName; 
  } 
  public void setFamilyName(String familyName) { 
    FamilyName = familyName; 
  } 
   
  @Column(name="FAMILY_CHARGE") 
  public String getFamilyCharge() { 
    return FamilyCharge; 
  } 
  public void setFamilyCharge(String familyCharge) { 
    FamilyCharge = familyCharge; 
  } 
   
  @Column(name="MOBILE") 
  public String getMobile() { 
    return Mobile; 
  } 
  public void setMobile(String mobile) { 
    Mobile = mobile; 
  } 
   
   
  @Column(name="EMAIL") 
  public String getEmail() { 
    return Email; 
  } 
  public void setEmail(String email) { 
    Email = email; 
  } 
   
  @Column(name="ADDRESS") 
  public String getAddress() { 
    return Address; 
  } 
  public void setAddress(String address) { 
    Address = address; 
  } 
   
  @Column(name="CREATE_DATA") 
  public Date getCreateData() { 
    return CreateData; 
  } 
  public void setCreateData(Date createData) { 
    CreateData = createData; 
  } 
  public FamilyMember() { 
    super(); 
    // TODO Auto-generated constructor stub 
  } 
  public FamilyMember(Integer id, String familyName, String familyCharge, String mobile, String email, String address, 
      Date createData) { 
    super(); 
    this.id = id; 
    FamilyName = familyName; 
    FamilyCharge = familyCharge; 
    Mobile = mobile; 
    Email = email; 
    Address = address; 
    CreateData = createData; 
  } 
 
   
} 

FamilyDao接口類:

package com.fendo.dao; 
 
import java.util.List; 
import java.util.Map; 
 
import org.springframework.data.jpa.repository.JpaSpecificationExecutor; 
import org.springframework.data.repository.PagingAndSortingRepository; 
 
import com.fendo.entity.FamilyMember; 
 
public interface FamilyDao extends PagingAndSortingRepository<FamilyMember, String>, JpaSpecificationExecutor<FamilyMember>{ 
 
 
} 

FamilyService服務(wù)接口類:

package com.fendo.service; 
 
import java.util.List; 
import java.util.Map; 
 
import com.fendo.entity.FamilyMember; 
 
public interface FamilyService { 
   
  public List<FamilyMember> getAll() throws Exception; 
   
  public FamilyMember save(FamilyMember familyMember) throws Exception; 
   
  public Map<String, Object> getUserBySearch(Map<String, String> familyArgs, final String sortType) throws Exception; 
 
} 

FamilyService服務(wù)接口實現(xiàn)類:

package com.fendo.service.imp; 
 
import java.util.ArrayList; 
import java.util.List; 
import java.util.Map; 
 
import javax.persistence.criteria.CriteriaBuilder; 
import javax.persistence.criteria.CriteriaQuery; 
 
import org.apache.commons.lang.StringUtils; 
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.data.domain.Page; 
import org.springframework.data.domain.Pageable; 
import org.springframework.data.jpa.domain.Specification; 
 
import javax.persistence.criteria.Predicate; 
import javax.persistence.criteria.Root; 
import javax.transaction.Transactional; 
 
import org.springframework.stereotype.Service; 
 
import com.fendo.dao.FamilyDao; 
import com.fendo.entity.FamilyMember; 
import com.fendo.service.FamilyService; 
import com.fendo.util.PageUtils; 
 
@Service 
@Transactional 
public class FamilyServiceImp implements FamilyService{ 
 
  @Autowired 
  public FamilyDao familyDao; 
     
  @Override 
  public List<FamilyMember> getAll() throws Exception { 
    return (List<FamilyMember>) this.familyDao.findAll(); 
  } 
 
  @Override 
  public FamilyMember save(FamilyMember familyMember) throws Exception { 
    return familyDao.save(familyMember); 
  } 
 
  /** 
   * 查詢用戶信息列表(支持分頁和多條件查詢)。 
   *  
   */ 
  @Override 
  public Map<String, Object> getUserBySearch(Map<String, String> familyArgs, final String sortType) throws Exception { 
 
    // 獲得分頁對象pageable,并且在pageable中頁碼是從0開始,設(shè)定按照sortType升序排列 
    Pageable pageable = PageUtils.buildPageRequest(Integer.valueOf(familyArgs.get("pageNum")), 
        Integer.valueOf(familyArgs.get("pageSize")), sortType); 
    Page<FamilyMember> objPage = familyDao.findAll(new Specification<FamilyMember>() { 
 
      public Predicate toPredicate(Root<FamilyMember> root, CriteriaQuery<&#63;> query, CriteriaBuilder cb) { 
        List<Predicate> lstPredicates = new ArrayList<Predicate>(); 
 
        if (StringUtils.isNotBlank(familyArgs.get("FamilyName"))) { 
          lstPredicates.add(cb.like(root.get("familyName").as(String.class), "%" + familyArgs.get("FamilyName") + "%")); 
        } 
        if (StringUtils.isNotBlank(familyArgs.get("Mobile"))) { 
          lstPredicates.add(cb.like(root.get("mobile").as(String.class), "%" + familyArgs.get("Mobile") + "%")); 
        } 
         
        Predicate[] arrayPredicates = new Predicate[lstPredicates.size()]; 
        return cb.and(lstPredicates.toArray(arrayPredicates)); 
      } 
    }, pageable); 
 
    return PageUtils.getPageMap(objPage); 
  } 
 
} 

前臺接受參數(shù)工具類:

package com.fendo.util; 
 
import java.util.HashMap; 
import java.util.Map; 
 
import javax.servlet.http.HttpServletRequest; 
 
/** 
 * 工具類 
 * @author fendo 
 * 
 */ 
public class FamilyUtil { 
 
  /** 
   * 封裝從前臺傳遞過來的查詢參數(shù)。 
   *  
   */ 
  public static Map<String, String> getSelArgsToMap(HttpServletRequest request) throws Exception { 
    Map<String, String> serArgs = new HashMap<String, String>(); 
 
    String FamilyName = request.getParameter("FamilyName"); 
    String Mobile = request.getParameter("Mobile"); 
 
     
    String pageNum = request.getParameter("pageNum") == null &#63; "1" : request.getParameter("pageNum"); 
    String pageSize = request.getParameter("pageSize") == null &#63; "10" : request.getParameter("pageSize"); 
 
    serArgs.put("FamilyName", FamilyName); 
    serArgs.put("Mobile", Mobile); 
     
    serArgs.put("pageNum", pageNum); 
    serArgs.put("pageSize", pageSize); 
 
    return serArgs; 
  } 
 
} 

分頁工具類:

package com.fendo.util; 
 
import java.util.HashMap; 
import java.util.Map; 
 
import org.apache.commons.lang3.StringUtils; 
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; 
 
public class PageUtils { 
 
  /** 
   * 封裝分頁數(shù)據(jù)到Map中。 
   */ 
  public static Map<String, Object> getPageMap(Page<&#63;> objPage) { 
     
    Map<String, Object> resultMap = new HashMap<String, Object>(); 
 
    resultMap.put("resultList", objPage.getContent()); // 數(shù)據(jù)集合 
    resultMap.put("totalNum", objPage.getTotalElements()); // 總記錄數(shù) 
    resultMap.put("totalPage", objPage.getTotalPages()); // 總頁數(shù) 
    resultMap.put("pageNum", objPage.getNumber()); // 當(dāng)前頁碼 
    resultMap.put("pageSize", objPage.getSize()); // 每頁顯示數(shù)量 
 
    return resultMap; 
  } 
 
  /** 
   * 創(chuàng)建分頁請求。 
   * 
   * @param pageNum 當(dāng)前頁 
   * @param pageSize 每頁條數(shù) 
   * @param sortType 排序字段 
   * @param direction 排序方向 
   */ 
  public static PageRequest buildPageRequest(int pageNum, int pageSize, String sortType, String direction) { 
    Sort sort = null; 
     
    if (!StringUtils.isNotBlank(sortType)) { 
      return new PageRequest(pageNum - 1, pageSize); 
    } else if (StringUtils.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); 
    } 
  } 
 
  /** 
   * 創(chuàng)建分頁請求(該方法可以放到util類中). 
   */ 
  public static PageRequest buildPageRequest(int pageNum, int pageSize, String sortType) { 
    return buildPageRequest(pageNum, pageSize, sortType, null); 
  } 
   
  /** 
   * 創(chuàng)建分頁請求 
   *  
   * @param pageNum 
   * @param pageSize 
   * @param sort 
   * @return 
   */ 
  public static PageRequest buildPageRequest(int pageNum, int pageSize, Sort sort) { 
    return new PageRequest(pageNum - 1, pageSize, sort); 
  } 
 
  /** 
   * 創(chuàng)建分頁請求(該方法可以放到util類中). 
   */ 
  public static PageRequest buildPageRequest(int pageNum, int pageSize) { 
    return buildPageRequest(pageNum, pageSize, null, null); 
  } 
 
} 

Controller類:

package com.fendo.controller; 
 
import java.util.HashMap; 
import java.util.List; 
import java.util.Map; 
 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 
 
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.stereotype.Controller; 
import org.springframework.ui.Model; 
import org.springframework.web.bind.annotation.RequestMapping; 
import org.springframework.web.servlet.ModelAndView; 
 
import com.fendo.entity.FamilyMember; 
import com.fendo.service.imp.FamilyServiceImp; 
import com.fendo.util.FamilyUtil; 
 
@Controller() 
@RequestMapping(value="DataTable") 
public class DataTableController { 
 
  @Autowired 
  public FamilyServiceImp FamilyMember; 
   
  @RequestMapping(value="/home_list") 
  public String home(Model model,HttpServletRequest request,HttpServletResponse response){ 
    Map<String, Object> resultMap = new HashMap<>(); 
    List<FamilyMember> list; 
    try { 
      list = FamilyMember.getAll(); 
      // 查詢表單或分頁保持請求時 請求參數(shù)的接收 
      Map<String, String> serArgs = new HashMap<String, String>(); 
      serArgs = FamilyUtil.getSelArgsToMap(request);//這個類在下面給出 
      resultMap = FamilyMember.getUserBySearch(serArgs, "CreateData"); //按創(chuàng)建時間排序 
      model.addAttribute("resultMap",resultMap); 
    } catch (Exception e) { 
      e.printStackTrace(); 
    } 
     
    return "datatable"; 
  } 
} 

首頁datatable.jsp

<%@ page language="java" contentType="text/html; charset=utf-8" 
  pageEncoding="utf-8"%> 
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 
<c:set var="ctx" value="${pageContext.request.contextPath}"/> 
<!DOCTYPE html> 
<html lang="zh-CN"> 
 <head> 
  <meta charset="utf-8"> 
  <meta http-equiv="X-UA-Compatible" content="IE=edge"> 
  <meta name="viewport" content="width=device-width, initial-scale=1"> 
  <!-- 上述3個meta標(biāo)簽*必須*放在最前面,任何其他內(nèi)容都*必須*跟隨其后! --> 
  <title>Spring Data JPA分頁示例</title> 
 
  <!-- Bootstrap --> 
  <link href="${ctx}/css/bootstrap.min.css" rel="external nofollow" rel="stylesheet"> 
   
  <!-- jQuery (necessary for Bootstrap's JavaScript plugins) --> 
  <script src="${ctx}/js/jquery-1.10.2.min.js"></script> 
   
   
  <!-- Include all compiled plugins (below), or include individual files as needed --> 
  <script src="${ctx}/js/bootstrap.min.js"></script> 
   
  <script type="text/javascript" src="${ctx}/js/kkpager.min.js"></script> 
  <link rel="stylesheet" type="text/css" href="${ctx}/css/kkpager_blue.css" rel="external nofollow" /> 
 </head> 
 <body> 
 
  
   <div class="container"> 
 
    <div > 
     <h3>Spring Data JPA分頁示例</h3> 
    </div> 
     
  
    <div class="panel panel-primary"> 
     
     <div class="panel-heading"> 
      <h4 class="panel-title">數(shù)據(jù)表格</h4> 
     </div> 
     
 
     
      <div class="panel-body" > 
       
  <form class="form-inline" id="searchForm" method="post" action="${ctx}/DataTable/home_list"> 
     
    <div class="row"> 
       
       
     <div class="form-group col-sm-3"> 
      <input type="checkbox" id="inlineCheckbox1" value="option1"> 
      <label>選擇所有</label> 
     </div> 
       
     <div class="form-group col-sm-3"> 
      <label>家庭名:</label> 
      <input type="input" name="FamilyName" id="FamilyName" class="form-control" id="exampleInputName3" placeholder="用戶名"> 
     </div> 
      
      
     <div class="form-group col-sm-3"> 
      <label>手機(jī)號:</label> 
 
       
      <input type="input" name="Mobile" id="Mobile" class="form-control" id="exampleInputMobile3" placeholder="手機(jī)號"></input> 
       
       
     </div> 
      
     <div class="col-sm-3"> 
      <button type="submit" class="btn btn-primary">搜索</button> 
      <button type="button" class="btn btn-primary">刪除</button> 
     </div> 
      
 
       
    </div> 
     
      
  </form> 
       
  <table class="table table-hover" > 
   <thead> 
    <tr> 
      <th></th> 
      <th>順序</th> 
      <th>家庭名稱</th> 
      <th>家庭Key</th> 
      <th>負(fù)責(zé)人</th> 
      <th>手機(jī)號</th> 
      <th>郵箱</th> 
      <th>家庭地址</th> 
      <th>創(chuàng)建時間</th> 
      <th>狀態(tài)</th> 
      <th>操作</th> 
    </tr> 
   </thead> 
   <tbody> 
    
    
    
   <c:forEach var="lise" items="${resultMap.resultList}" varStatus="status"> 
     <tr> 
       <td><input type="checkbox" id="inlineCheckbox1" value="option1"></td> 
       <th scope="row">${status.index+1}</th> 
       <td>${lise.familyName}</td> 
       <td>${lise.id}</td> 
       <td>${lise.familyCharge}</td> 
       <td>${lise.mobile }</td> 
       <td>${lise.email}</td> 
       <td>${lise.address}</td> 
       <td>${lise.createData}</td> 
       <td>啟用</td> 
       <td><a href="#" rel="external nofollow" >編輯</a></td> 
      </tr> 
     
   </c:forEach> 
    
   
     
 
    
   </tbody> 
  </table> 
       
      </div> 
    </div> 
     
    <div > 
     
    <div id="kkpager"></div> 
     
    </div> 
     
   
  </div> 
   
  <script> 
   
  var param = ""; 
   
   
  $(function() { 
    var totalPage = "${resultMap.totalPage}"; 
    var totalRecords = "${resultMap.totalNum}"; 
    var pageSize = "${resultMap.pageSize}"; 
 
    var pageNum = parseInt("${resultMap.pageNum}") + 1; 
    //初始化分頁控件 
    //有些參數(shù)是可選的,比如lang,若不傳有默認(rèn)值 
    kkpager.init({ 
      pno: pageNum, 
      //總頁碼 
      total: "${resultMap.totalPage}", 
      //總數(shù)據(jù)條數(shù) 
      totalRecords: totalRecords, 
      //鏈接前部 
      hrefFormer: '${ctx}/DataTable/home_list', 
      //鏈接尾部 
      hrefLatter: '', 
      getLink: function(n) { 
        return getInitParam() + "&pageNum=" + n + "&pageSize=" + pageSize; 
      }, 
      lang: { 
        prePageText: '上一頁', 
        nextPageText: '下一頁', 
        totalPageBeforeText: '共', 
        totalPageAfterText: '頁', 
        totalRecordsAfterText: '條數(shù)據(jù)', 
        gopageBeforeText: '轉(zhuǎn)到', 
        gopageButtonOkText: '確定', 
        gopageAfterText: '頁', 
        buttonTipBeforeText: '第', 
        buttonTipAfterText: '頁' 
      } 
    }); 
    //生成 
    kkpager.generPageHtml(); 
 
    $('#mykkpagerselect').val(pageSize); 
  }); 
   
   
  function getInitParam() { 
    var FamilyName = $('#FamilyName').val(); 
    var Mobile = $('#Mobile').val(); 
 
    var attr = "&#63;FamilyName=" + encodeURI(encodeURI(FamilyName))  
        + "&Mobile=" + Mobile; 
    return "${ctx}/DataTable/home_list" + attr; 
  } 
 
  /** 
   * 搜索。 
   */ 
  function search() { 
    $('#searchForm').submit(); 
  }   
   
 
  </script> 
 
 </body> 
</html> 

看完上述內(nèi)容,你們掌握Spring Data中的分頁功能如何留 JPA+kkpager實現(xiàn)的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝各位的閱讀!

網(wǎng)頁標(biāo)題:SpringData中的分頁功能如何留JPA+kkpager實現(xiàn)
路徑分享:http://bm7419.com/article46/pscceg.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供、微信小程序、網(wǎng)站建設(shè)域名注冊、網(wǎng)站策劃、定制開發(fā)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

h5響應(yīng)式網(wǎng)站建設(shè)