1. 程式人生 > >Springboot+Mybatis+PageHelper快速實現分頁功能

Springboot+Mybatis+PageHelper快速實現分頁功能

話不多說,直接上乾貨:

pom檔案:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.zhaojun</groupId>
	<artifactId>websocket-test</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>websocket-test</name>
	<description>Demo project for Spring Boot</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.2.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>com.github.pagehelper</groupId>
			<artifactId>pagehelper-spring-boot-starter</artifactId>
			<version>1.2.3</version>
		</dependency>
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid</artifactId>
			<version>1.0.15</version>
		</dependency>
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<version>1.16.18</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>


</project>

springboot配置檔案application.yml:

pagehelper:
  reasonable: true
  support-methods-arguments: true
  params: count=countSql
  helper-dialect: mysql


spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/db_name?useSSL=true&characterEncoding=UTF-8
    username: root
    password: root
    maxActive: 20
    initialSize: 1
    maxWait: 60000
    minIdle: 1
    timeBetweenEvictionRunsMillis: 60000
    minEvictableIdleTimeMillis: 300000
    validationQuery: select 'x'
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    poolPreparedStatements: true
    maxOpenPreparedStatements: 20

mybatis:
  mapper-locations: classpath:mapper/**/*.xml

controller程式碼:

package com.zhaojun.user.controller;

import com.zhaojun.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 使用者controller
 *
 * @author ZhaoJun
 */
@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/users")
    public Object usersData(int pageNum, int pageSize) {
        return userService.usersData(pageNum, pageSize);
    }
}

service:

package com.zhaojun.user.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zhaojun.user.dao.UserDao;
import com.zhaojun.user.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 使用者Service
 *
 * @author ZhaoJun
 */
@Service
public class UserService  {

    @Autowired
    private UserDao userDao;

    public Object usersData(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<User> users = userDao.usersData();
        PageInfo<User> appsPageInfo = new PageInfo<>(users);
        return appsPageInfo;
    }
}

dao程式碼:

package com.zhaojun.user.dao;

import com.zhaojun.user.entity.User;

import java.util.List;

/**
 * 使用者Dao
 *
 * @author ZhaoJun
 */
public interface UserDao {

    List<User> usersData();

}

daoImpl程式碼:

package com.zhaojun.user.dao.impl;

import com.zhaojun.user.dao.UserDao;
import com.zhaojun.user.entity.User;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @author ZhaoJun
 */
@Repository
public class UserDaoImpl implements UserDao {

    @Autowired
    private SqlSession sqlSession;

    @Override
    public List<User> usersData() {
        return sqlSession.selectList("selectUsers");
    }
}

mapper檔案:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.ardsec.user.dao.impl.UserDaoImpl">

    <!-- 結果對映 -->
    <resultMap id="userResult" type="com.zhaojun.user.entity.User" >
        <id column="id" property="id" jdbcType="VARCHAR" />
        <result column="user_name" property="userName" jdbcType="VARCHAR" />
        <result column="login_name" property="loginName" jdbcType="VARCHAR" />
        <result column="password" property="password" jdbcType="VARCHAR" />
        <result column="tel" property="tel" jdbcType="VARCHAR" />
        <result column="role" property="role" jdbcType="VARCHAR" />
        <result column="org" property="org" jdbcType="VARCHAR" />
    </resultMap>

    <select id="selectUsers" resultMap="userResult">
        SELECT * from user WHERE org IS NULL
    </select>

</mapper>

sql檔案:

/*
Navicat MySQL Data Transfer

Source Server         : localhost
Source Server Version : 50722
Source Host           : localhost:3306
Source Database       : adamas

Target Server Type    : MYSQL
Target Server Version : 50722
File Encoding         : 65001

Date: 2018-08-16 19:00:36
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` varchar(64) NOT NULL COMMENT '主鍵id',
  `login_name` varchar(200) DEFAULT NULL COMMENT '登陸賬號',
  `user_name` varchar(200) DEFAULT NULL COMMENT '使用者名稱',
  `password` varchar(255) DEFAULT NULL COMMENT '密碼',
  `tel` varchar(64) DEFAULT NULL COMMENT '電話號碼',
  `org` varchar(64) DEFAULT NULL COMMENT '機構',
  `role` varchar(200) DEFAULT NULL COMMENT '角色',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='使用者表';

-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1223456789', null, 'qq', null, null, null, null);
INSERT INTO `user` VALUES ('122345689', null, 'wwwwww', null, null, null, null);
INSERT INTO `user` VALUES ('12234589', null, 'eeeeeee', null, null, null, null);
INSERT INTO `user` VALUES ('1223489', null, 'rrrrrrr', null, null, null, null);
INSERT INTO `user` VALUES ('122389', null, 'ttttt', null, null, null, null);
INSERT INTO `user` VALUES ('12289', null, 'yyyyyyyyyyy', null, null, null, null);
INSERT INTO `user` VALUES ('123', null, 'uuuuuuuu', null, null, null, null);
INSERT INTO `user` VALUES ('1234', null, 'iiiiiiiiiii', null, null, null, null);
INSERT INTO `user` VALUES ('12345', null, 'aaaaaaa', null, null, null, null);
INSERT INTO `user` VALUES ('123456', null, 'sssssssss', null, null, null, null);
INSERT INTO `user` VALUES ('1234567', null, 'dddddddd', null, null, null, null);
INSERT INTO `user` VALUES ('12345678', null, 'fffffffff', null, null, null, null);
INSERT INTO `user` VALUES ('123456789', null, 'gggggggg', null, null, null, null);
INSERT INTO `user` VALUES ('1289', null, 'hhhhhhhhh', null, null, null, null);
INSERT INTO `user` VALUES ('18ce23a9027b4fe29e7a9c5b4828a20b', 'lsmife', 'lshis', '0a113ef6b61820daa5611c870ed8d5ee', '18000000000', '工商銀行', 'usual');
INSERT INTO `user` VALUES ('8197fdc71d7a4838b2d81fccdc150ac1', 'lshis', 'Mr.Li', 'b706835de79a2b4e80506f582af3676a', '18899998888', '金融集團', 'usual');
INSERT INTO `user` VALUES ('868560ec718d4cb5a969ab8ccdb54ac7', 'admin', 'admin', '123456', '15512345678', 'root', 'admin');

小夥伴們 就此結束