Spring Data Jpa+SpringMVC+Jquery.pagination.js实现分页示例

本博客介绍基于Spring Data这款orm框架加上 Jquery.pagination插件实现的分页功能。

本博客是基于一款正在开发中的github开源项目的,项目代码地址:https://github.com/u014427391/jeeplatform

欢迎star(收藏)或者可以下载去学习,还在开发…

介绍一下Spring Data框架

spring Data : Spring 的一个子项目。用于简化数据库访问,支持NoSQL 和 关系数据存储。

下面给出SpringData 项目所支持 NoSQL 存储:

* MongoDB (文档数据库)
* Neo4j(图形数据库)
* Redis(键/值存储)
* Hbase(列族数据库)

SpringData 项目所支持的关系数据存储技术:

* JDBC
* JPA

JPA Spring Data : 致力于减少数据访问层 (DAO) 的开发量。开发者只要写好持久层接口就好,然后其它的框架会帮程序员实现。

开发步骤:

【Spring Data实现数据获取】

本项目是采用maven的,所以可以参考一下我的maven配置:


  
    muses
    org.muses
    1.0-SNAPSHOT
  
  4.0.0
  jeeplatform-admin
  war
  jeeplatform-admin Maven Webapp
  http://maven.apache.org
  
    4.1.5.RELEASE
    1.4.2.RELEASE
    1.6.2.RELEASE
    4.3.8.Final
    1.2.3
    4.7.2
    1.0.9
    3.7
  

  
    
    
      org.muses
      jeeplatform-core
      ${jeeplatform.core.version}
    
    
      org.muses
      jeeplatform-common
      1.0-SNAPSHOT
    
    
      org.muses
      jeeplatform-oss
      ${jeeplatform.oss.version}
    
    
      org.muses
      jeeplatform-upms
      1.0-SNAPSHOT
    
    
    
    
      javax.servlet
      servlet-api
      2.5
      provided
    
    
    
    
      jstl
      jstl
      1.2
    
    
      taglibs
      standard
      1.1.2
    
    
    
    
      log4j
      log4j
      ${log4j.version}
    
    
    
    
      commons-beanutils
      commons-beanutils
      1.8.3
    
    
      commons-collections
      commons-collections
      3.2.1
    
    
      net.sf.ezmorph
      ezmorph
      1.0.6
    
    
      commons-lang
      commons-lang
      2.5
    
    
      commons-logging
      commons-logging
      1.2
    
    
      net.sf.json-lib
      json-lib
      2.4
      jar
      jdk15
      compile
    
    
    
    
      mysql
      mysql-connector-java
      ${mysql.version}
    
    
    
    
      commons-io
      commons-io
      2.0.1
    
    
      commons-fileupload
      commons-fileupload
      1.2.2
    
    
    
    
      org.springframework
      spring-core
      ${spring.version}
    
    
      org.springframework
      spring-beans
      ${spring.version}
    
    
      org.springframework
      spring-context
      ${spring.version}
    
    
      org.springframework
      spring-context-support
      ${spring.version}
    
    
      org.springframework
      spring-jdbc
      ${spring.version}
    
    
      org.springframework
      spring-tx
      ${spring.version}
    
    
      org.springframework
      spring-test
      ${spring.version}
      test
    
    
      org.springframework
      spring-web
      ${spring.version}
    
    
    
    
      org.springframework
      spring-aop
      ${spring.version}
    
    
      org.aspectj
      aspectjweaver
      1.6.10
    
    
    
    
      org.springframework
      spring-webmvc
      ${spring.version}
    
    
    
    
      org.springframework
      spring-orm
      ${spring.version}
    
    
      org.springframework.data
      spring-data-jpa
      ${spring-data-jpa.version}
    
    
      org.springframework.data
      spring-data-commons
      ${spring-data-commons.version}
    
    
    
    
      org.hibernate.javax.persistence
      hibernate-jpa-2.1-api
      1.0.0.Final
    
    
      org.hibernate
      hibernate-core
      ${hibernate.version}
    
    
      org.hibernate
      hibernate-entitymanager
      ${hibernate.version}
    
    
    
    
      org.slf4j
      slf4j-api
      1.6.1
    
    
      net.sf.ehcache
      ehcache-core
      2.5.0
    
    
      org.hibernate
      hibernate-ehcache
      ${hibernate.version}
    
    
    
    
      com.alibaba
      druid
      ${druid.version}
    
    
    
    
      org.apache.shiro
      shiro-all
      ${shiro.version}
    
    
    
    
      org.apache.velocity
      velocity
      1.6
    
    
      org.apache.velocity
      velocity-tools
      2.0
    
    
    
    
      org.apache.lucene
      lucene-core
      ${lucene.version}
    
    
      org.apache.lucene
      lucene-analyzers-common
      ${lucene.version}
    
    
      org.apache.lucene
      lucene-queryparser
      ${lucene.version}
    
    
      org.apache.lucene
      lucene-memory
      ${lucene.version}
    
    
      org.apache.lucene
      lucene-highlighter
      ${lucene.version}
    
    
    
      org.wltea.analyzer
      IKAnalyzer
      2012FF_u1
      system
      ${basedir}/src/main/webapp/WEB-INF/lib/IKAnalyzer2012FF_u1.jar
    
    
    
    
      log4j
      log4j
      ${log4j.version}
    
    
    
    
      commons-beanutils
      commons-beanutils
      1.8.3
    
    
      commons-collections
      commons-collections
      3.2.1
    
    
      net.sf.ezmorph
      ezmorph
      1.0.6
    
    
      commons-lang
      commons-lang
      2.5
    
    
      commons-logging
      commons-logging
      1.2
    
    
      net.sf.json-lib
      json-lib
      2.4
      jar
      jdk15
      compile
    
    
    
    
      org.apache.poi
      poi
      ${poi.version}
    
    
    
    
      com.sun.mail
      javax.mail
      1.5.6
    
    
  
  
    jeeplatform-admin
  


设计好数据库,编写一个实体类:

Spring Data Jpa+SpringMVC+Jquery.pagination.js实现分页示例_第1张图片

package org.muses.jeeplatform.model.entity;
import java.util.Date;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
 * 用户信息的实体类
 * @author Nicky
 */
@Entity
@Table(name="sys_user")
public class User {
  /** 用户Id**/
  private int id;

  /** 用户名**/
  private String username;

  /** 用户密码**/
  private String password;

  /** 手机号**/
  private int phone;

  /** 性别**/
  private String sex;

  /** 邮件**/
  private String email;

  /** 备注**/
  private String mark;

  /** 用户级别**/
  private String rank;

  /** 最后一次时间**/
  private Date lastLogin;

  /** 登录ip**/
  private String loginIp;

  /** 图片路径**/
  private String imageUrl;

  /** 注册时间**/
  private Date regTime;

  /** 账号是否被锁定**/
  private Boolean locked = Boolean.FALSE;

  private Set roles;    

  @GeneratedValue(strategy=GenerationType.IDENTITY)
  @Id
  public int getId() {
    return id;
  }

  public void setId(int id) {
    this.id = id;
  }

  @Column(unique=true,length=100,nullable=false)
  public String getUsername() {
    return username;
  }

  public void setUsername(String username) {
    this.username = username;
  }

  @Column(length=100,nullable=false)
  public String getPassword() {
    return password;
  }

  public void setPassword(String password) {
    this.password = password;
  }

  public int getPhone() {
    return phone;
  }

  public void setPhone(int phone) {
    this.phone = phone;
  }

  @Column(length=6)
  public String getSex() {
    return sex;
  }

  public void setSex(String sex) {
    this.sex = sex;
  }

  @Column(length=100)
  public String getEmail() {
    return email;
  }

  public void setEmail(String email) {
    this.email = email;
  }

  @Column(length=30)
  public String getMark() {
    return mark;
  }

  public void setMark(String mark) {
    this.mark = mark;
  }

  @Column(length=10)
  public String getRank() {
    return rank;
  }

  public void setRank(String rank) {
    this.rank = rank;
  }

  @Temporal(TemporalType.DATE)
  public Date getLastLogin() {
    return lastLogin;
  }

  public void setLastLogin(Date lastLogin) {
    this.lastLogin = lastLogin;
  }

  @Column(length=100)
  public String getLoginIp() {
    return loginIp;
  }

  public void setLoginIp(String loginIp) {
    this.loginIp = loginIp;
  }

  @Column(length=100)
  public String getImageUrl() {
    return imageUrl;
  }

  public void setImageUrl(String imageUrl) {
    this.imageUrl = imageUrl;
  }

  @Temporal(TemporalType.DATE)
  @Column(nullable=false)
  public Date getRegTime() {
    return regTime;
  }

  public void setRegTime(Date regTime) {
    this.regTime = regTime;
  }

   public Boolean getLocked() {
    return locked;
  }

  public void setLocked(Boolean locked) {
    this.locked = locked;
  }

}

编写接口实现Spring Data框架的PagingAndSortingRepository接口

package org.muses.jeeplatform.repository;
import org.muses.jeeplatform.model.entity.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import java.util.Date;

public interface UserRepository extends PagingAndSortingRepository {
  /*User findByUsername(String username);
  @Query("from User u where u.username=:username and u.password=:password")
  User findByUsernameAndPassword(@Param("username") String username, @Param("password") String password);

  @Query("from User u where u.id=:id")
  User findById(@Param("id") int id);

  @Query("from User u where date_format(u.lastLogin,'yyyy-MM-dd') between date_format((:startDate),'yyyy-MM-dd') and date_format((:endDate),'yyyy-MM-dd')")
  Page searchU(@Param("startDate")Date startDate,@Param("endDate")Date endDate, Pageable pageable);
*/
}

业务类实现:

package org.muses.jeeplatform.service;
import java.util.*;
import org.muses.jeeplatform.model.entity.User;
import org.muses.jeeplatform.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
/**
 * @description 用户信息管理的业务类
 * @author Nicky 
 * @date 2017年3月6日
 */
@Service
public class UserService {
  @Autowired
  UserRepository userRepository;
  /**
   * 构建PageRequest对象
   * @param num
   * @param size
   * @param asc
   * @param string
   * @return
   */
  private PageRequest buildPageRequest(int num, int size, Sort.Direction asc,
                     String string) {
    return new PageRequest(num-1, size,null,string);
  }

  /**
   * 获取所有的菜单信息并分页显示
   * @param pageNo
   *     当前页面数
   * @param pageSize
   *     每一页面的页数
   * @return
   */
  @Transactional
  public Page findAll(int pageNo, int pageSize, Sort.Direction dir, String str){
    PageRequest request = buildPageRequest(pageNo, pageSize, dir, str);
    Page users = userRepository.findAll(request);
    return users;
  }
}

控制类,采用SpringMVC框架,先编写一个baseController,实现一些通用功能的封装:

package org.muses.jeeplatform.web.controller;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;
public class BaseController {
  Logger log = null;
  /**
   * 获取日志对象
   * @return
   */
  public Logger getInstance(){
    if(log == null){
      log = LoggerFactory.getLogger(BaseController.class);
    }
    return log;
  }

  /**
   * 得到request对象
   */
  public HttpServletRequest getRequest() {
    HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
    return request;
  }

  /**
   * 得到ModelAndView
   */
  public ModelAndView getModelAndView(){
    return new ModelAndView();
  }
}

控制类实现:

package org.muses.jeeplatform.web.controller;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import org.apache.commons.collections.map.HashedMap;
import org.muses.jeeplatform.core.Constants;
import org.muses.jeeplatform.core.ExcelViewWrite;
import org.muses.jeeplatform.core.JavaEmailSender;
import org.muses.jeeplatform.model.entity.User;
import org.muses.jeeplatform.service.UserService;
import org.muses.jeeplatform.utils.DateJsonValueProcessor;
import org.muses.jeeplatform.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.*;
/**
 * Created by Nicky on 2017/7/29.
 */
@RequestMapping("/user")
@Controller
public class UserController extends BaseController{
  @Autowired
  UserService userService;
  /**
   * 查询所有管理员信息并分页显示
   * @param request
   * @param response
   * @param model
   * @return
   */
  @RequestMapping(value = "/queryAll",produces = "application/json;charset=UTF-8")
  @ResponseBody
  public ModelAndView findAll(HttpServletRequest request, HttpServletResponse response, Model model){
    //当前页
    String pageIndexStr = request.getParameter("pageIndex");

    //每一页的页数
    int pageSize = Constants.PAGE_SIZE;
    ModelAndView mv = this.getModelAndView();
    Page userPage;

    if(pageIndexStr==null||"".equals(pageIndexStr)){
      pageIndexStr = "0";
    }
    int pageIndex = Integer.parseInt(pageIndexStr);
    userPage = userService.findAll(pageIndex+1, pageSize, Sort.Direction.ASC,"id");
    mv.addObject("totalCount",userPage.getTotalElements());
    mv.addObject("pageIndex",pageIndex);
//    JsonConfig cfg = new JsonConfig();
//    cfg.setExcludes(new String[]{"handler","hibernateLazyInitializer"});
    JsonConfig jcg = new JsonConfig();
    jcg.registerJsonValueProcessor(Date.class,
        new DateJsonValueProcessor("yyyy-mm-dd"));
    JSONArray jsonArray = JSONArray.fromObject(userPage.getContent(),jcg);
    //System.out.println(jsonArray.toString());
    mv.addObject("users",jsonArray.toString());
    mv.setViewName("admin/user/sys_user_list");
    return mv;
  }
}

 【前端页面实现】

页面View实现,引用 jquery.pagination.js (分页js),跟pagination.css(分页样式css)。

可以去这里下载://www.jb51.net/article/105013.htm

<%@ page contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%
  String path = request.getContextPath();
  String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>



  
  
  
  
  Insert title here
  
  
  
  
  
  
  
  





序号 用户名 描述 手机 邮箱 最近登录 上次登录IP 操作

前端页面展示:

Spring Data Jpa+SpringMVC+Jquery.pagination.js实现分页示例_第2张图片

ok,本博客是基于一款正在开发中的github开源项目的,项目代码地址:https://github.com/u014427391/jeeplatform

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

你可能感兴趣的:(Spring Data Jpa+SpringMVC+Jquery.pagination.js实现分页示例)