Spring Boot Integration Tutorial
- Spring Boot Introduction
- Spring Boot development environment to build (Eclipse)
- Spring Boot Hello World (restful Interface) Examples
- spring boot connect Mysql
- spring boot configuration druid connection pool mysql
- Integrated spring boot mybatis (1)
- Integrated spring boot mybatis (2) - used to implement paging pagehelper
- Integrated spring boot mybatis (3) - mybatis generator arranged
- Interface package return spring boot value
- input data check spring boot (Validation)
- spring boot rest interface Integrated spring security (1) - the most simple configuration
- Interface integrated spring boot rest spring security (2) - JWT Configuration
- spring boot exception (Exception) Processing
- spring boot environment configuration (Profile) switch
- spring boot redis cache (cache) Integration
Outline
In this paper the basis of the previous tutorial, using a common pagehelper plug-ins, add paging functionality. This article will implement a list of all user interface, paged return results
Prepare data
Database data tables and use the previous section [spring boot integrated mybatis (1)] is used, due to the tab, insertion need more data table.
mysql command-line client database connection
mysql -h localhost -u root -p
Insert data sql statement:
INSERT INTO `qikegu_demo`.`user` (`nickname`, `mobile`, `password`) VALUES ('abc3', '13512345603', '123');
INSERT INTO `qikegu_demo`.`user` (`nickname`, `mobile`, `password`) VALUES ('abc4', '13512345604', '123');
INSERT INTO `qikegu_demo`.`user` (`nickname`, `mobile`, `password`) VALUES ('abc5', '13512345605', '123');
INSERT INTO `qikegu_demo`.`user` (`nickname`, `mobile`, `password`) VALUES ('abc6', '13512345606', '123');
INSERT INTO `qikegu_demo`.`user` (`nickname`, `mobile`, `password`) VALUES ('abc7', '13512345607', '123');
INSERT INTO `qikegu_demo`.`user` (`nickname`, `mobile`, `password`) VALUES ('abc8', '13512345608', '123');
INSERT INTO `qikegu_demo`.`user` (`nickname`, `mobile`, `password`) VALUES ('abc9', '13512345609', '123');
INSERT INTO `qikegu_demo`.`user` (`nickname`, `mobile`, `password`) VALUES ('abc10', '13512345610', '123');
Project Dependencies
Do not create a new project, reuse sections [spring boot integrated mybatis (1)] in the project, the project does not create according to the paper.
Eclipse open the item, in pom.xml file, adding a dependency: pagehelper-spring-boot-starter , the introduction of dependent packages pagehelper
Add Dependency: pagehelper-spring-boot-starter
Add depend in pom.xml
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.10</version>
</dependency>
Complete pom.xml file
<?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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.qikegu</groupId>
<artifactId>springboot-mybatis-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot-mybatis-demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper-spring-boot-starter -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.10</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Project Configuration
Add pagehelper Configuration
Add pagehelper configuration in application.properties
pagehelper.helperDialect=mysql
pagehelper.reasonable=true
pagehelper.supportMethodsArguments=true
pagehelper.params=count=countSql
Description:
helperDialect
: Pagination plug-in will automatically detect the current database link, automatically selects the appropriate way paging. You can also configure helperDialect attribute to specify which dialect to use plug-ins page.reasonable
: Page rationalizing parameter, the default value is false. When this parameter is set to true, pageNum <= 0, the first page queries, pageNum> pages (more than the total number), the last page queries. Default false, according to a direct query parameters.params
: A property name from the subject according to the value, may be configured pageNum, pageSize, count, pageSizeZero, reasonable, not configured with a default value map, the default value pageNum = pageNum; pageSize = pageSize; count = countSql; reasonable = reasonable ; pageSizeZero = pageSizeZerosupportMethodsArguments
Default: false, pagination plug-in will automatically based on field values in the above params configuration parameters from the query method, the page will automatically find the time to the appropriate value.
More information pagehelper official website
Full content application.properties
## 服务器端口,如果不配置默认是8080端口
server.port=8096
## 数据库设置
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://192.168.0.99:3306/qikegu_demo?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=qazwsx
## mybatis配置
# 指向映射类目录
mybatis.type-aliases-package=com.qikegu.demo.model
# 指向映射xml文件目录
mybatis.mapper-locations=classpath:mapper/*.xml
## pagehelper
pagehelper.helperDialect=mysql
pagehelper.reasonable=true
pagehelper.supportMethodsArguments=true
pagehelper.params=count=countSql
Add code
pagehelper use
There are several methods pagehelper use, here we introduce the most commonly used two kinds:
//方法1,Mapper接口方式的调用,推荐这种使用方式。
PageHelper.startPage(1, 10); // pageNum=1, pageSize=10
List<Country> list = countryMapper.selectIf(1);
//方法2,参数方法调用
//存在以下 Mapper 接口方法,你不需要在 xml 处理后两个参数
public interface CountryMapper {
List<Country> selectByPageNumSize(
@Param("user") User user,
@Param("pageNum") int pageNum,
@Param("pageSize") int pageSize);
}
//配置supportMethodsArguments=true
//在代码中直接调用:
List<Country> list = countryMapper.selectByPageNumSize(user, 1, 10);
This article take the example of Method 1, more Reference pagehelper official website
Code
Add features we want to achieve: list all users, paging returns the result. The following documents need to modify a few:
- UserController.java - control layer
- UserService.java & UserServiceImpl.java - service layer
- UserMapper.java & UserMapper.xml - Data Access Layer
Figure:
UserController.java
Add a function
@RequestMapping(value="", method = RequestMethod.GET, produces="application/json")
public PageInfo<User> listUser(
@RequestParam(value="page", required=false, defaultValue="1") int page,
@RequestParam(value="page-size", required=false, defaultValue="5") int pageSize){
List<User> result = userService.listUser(page, pageSize);
// PageInfo包装结果,返回更多分页相关信息
PageInfo<User> pi = new PageInfo<User>(result);
return pi;
}
Description :
This function is a control layer interface, wherein
@RequestParam
Notes get the url?page=1&page-size=5
parametervalue="page"
is the parameter name in the url,required
refers to whether the parameters must, if it is necessary but not this URL parameter error,defaultValue="1"
the default valuePageInfo
PageInfo packaging results, returns more information about pagination
Complete code:
package com.qikegu.demo.controller;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.PathVariable;
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.RestController;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qikegu.demo.model.User;
import com.qikegu.demo.service.UserService;
@RestController
@EnableAutoConfiguration
@RequestMapping("/user")
public class UserController {
// 注入mapper类
@Resource
private UserService userService;
@RequestMapping(value="{id}", method=RequestMethod.GET, produces="application/json")
public User getUser(@PathVariable long id) throws Exception {
User user = this.userService.getUserById(id);
return user;
}
@RequestMapping(value="", method = RequestMethod.GET, produces="application/json")
public PageInfo<User> listUser(
@RequestParam(value="page", required=false, defaultValue="1") int page,
@RequestParam(value="page-size", required=false, defaultValue="5") int pageSize){
List<User> result = userService.listUser(page, pageSize);
// PageInfo包装结果,返回更多分页相关信息
PageInfo<User> pi = new PageInfo<User>(result);
return pi;
}
}
UserService.java & UserServiceImpl.java
UserService.java add an interface
public List<User> listUser(int page, int pageSize);
UserServiceImpl.java new implementation of the interface above
@Override
public List<User> listUser(int page, int pageSize) {
List<User> result = null;
try {
// 调用pagehelper分页,采用starPage方式。starPage应放在Mapper查询函数之前
PageHelper.startPage(page, pageSize); //每页的大小为pageSize,查询第page页的结果
PageHelper.orderBy("id ASC "); //进行分页结果的排序
result = userMapper.selectUser();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
Description:
See the code comments
Complete code:
UserService.java
package com.qikegu.demo.service;
import java.util.List;
import com.qikegu.demo.model.User;
public interface UserService {
public User getUserById(long userId);
public List<User> listUser(int page, int pageSize);
}
UserServiceImpl.java
package com.qikegu.demo.service.impl;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.github.pagehelper.PageHelper;
import com.qikegu.demo.model.User;
import com.qikegu.demo.repository.UserMapper;
import com.qikegu.demo.service.UserService;
@Service("userService")
public class UserServiceImpl implements UserService {
//注入mybatis数据库查询类
@Resource
private UserMapper userMapper;
@Override
public User getUserById(long userId) {
return userMapper.selectByPrimaryKey(userId);
}
@Override
public List<User> listUser(int page, int pageSize) {
List<User> result = null;
try {
// 调用pagehelper分页,采用starPage方式。starPage应放在Mapper查询函数之前
PageHelper.startPage(page, pageSize); //每页的大小为pageSize,查询第page页的结果
PageHelper.orderBy("id ASC "); //进行分页结果的排序
result = userMapper.selectUser();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
UserMapper.java & UserMapper.xml
UserMapper.java New Interface
// 列出用户,对应xml映射文件元素的ID
List<User> selectUser();
The interface UserMapper.xml achieve new mybatis xml
<select id="selectUser" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from user
</select>
Explanation
See the code comments
The complete code
UserMapper.java
package com.qikegu.demo.repository;
import java.util.List;
import com.qikegu.demo.model.User;
public interface UserMapper {
// 查询某个用户,对应xml映射文件元素的ID
User selectByPrimaryKey(long id);
// 列出用户,对应xml映射文件元素的ID
List<User> selectUser();
}
UserMapper.xml
<?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.qikegu.demo.repository.UserMapper">
<resultMap id="BaseResultMap" type="com.qikegu.demo.model.User">
<constructor>
<idArg column="id" javaType="_long" jdbcType="BIGINT" />
<arg column="nickname" javaType="java.lang.String" jdbcType="VARCHAR" />
<arg column="mobile" javaType="java.lang.String" jdbcType="VARCHAR" />
<arg column="password" javaType="java.lang.String" jdbcType="CHAR" />
<arg column="role" javaType="java.lang.String" jdbcType="VARCHAR" />
</constructor>
</resultMap>
<sql id="Base_Column_List">
id, nickname, mobile, password, role
</sql>
<select id="selectByPrimaryKey" parameterType="_long" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from user
where id = #{id,jdbcType=BIGINT}
</select>
<select id="selectUser" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from user
</select>
</mapper>
run
Eclipse on the left, right click on the project root directory pop-up menu, choose: run as -> spring boot app
run the program.
We use Postman access interface, Postman is a very powerful interface testing tool, it is commonly regarded as "essential travel home," it recommended. Installation is very simple, go to the official website to download it and follow the steps to install it. Results are as follows:
to sum up
Paging function can be said to be an essential feature of web development, this basic tutorial on the front, introduces the integration process mybatis pagehelper plug, pagehelper is a common pagination plug-ins, and have completely decoupled Mapper.xml advantages, recommended for use in the project.