Mybatis-Plus 分頁插件
前言
參考文檔:https://mp.baomidou.com/guide/page.html
筆者使用的是SpringBoot結合Mybatis-Plus。
如果讀者對SpringBoot創建項目已經熟悉,或者只想了解分頁插件的內容,請直接看章節”使用Mybatis-Plus分頁插件“。
工程結構
准備
首先,創建SpringBoot項目,實現從前端到后台跑通。
創建Maven工程
因為我已經創建過了,這里爆紅。
修改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.example</groupId>
<artifactId>mybatis-plus-pagination</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.6.RELEASE</version>
</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>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
<!--lombok簡化開發插件-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.2</version>
</dependency>
<!--jdbc-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!--springboot支持的是jpa,mybatisplus自己做了啟動器-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.1.2</version>
</dependency>
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!--spring-test-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
</dependencies>
<!--maven插件-->
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
編寫yml文件
在 resource文件夾下創建application.yml
# 端口
server:
port: 8080
# 數據源
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/springbootdemo?characterEncoding=utf-8&useSSL=false
username: root
password: root
# mybatis-plus設置
mybatis-plus:
mapper-locations: classpath:mapper/*.xml #mapper.xml文件位置,如果沒有映射文件,請注釋掉。
注:這里的數據庫名稱、用戶名和密碼記得改成自己的。
useSSL=false,是為了去掉一個檢測,不至於控制台報紅,不影響運行。
啟動類
創建Application.java
package com.example;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.example.mapper")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
@MapperScan 用來掃描Mapper文件
業務類
這部分內容包擴:實體類、Dao、Service、Controller
實體類
User.java
import java.io.Serializable;
@Data
@TableName("user")
public class User implements Serializable {
@TableId(type = IdType.AUTO, value = "userId") //自增
private Long userId;
@TableField(value = "userName")
private String userName;
@TableField(value = "password")
private String password;
@TableField(value = "status")
private int status;
}
@Data為lombok注解
@TableName 用來映射數據表名稱
@TableId 用來映射主鍵,value屬性用來映射字段名稱
如果不指定,mybatis-plus會根據屬性名自動映射,如“userId”映射為“user_id"。
Result.java 統一的前端返回類型
package com.example.entities;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Result implements Serializable {
private boolean success;
private String message;
private Object data;
public Result(boolean success, String message) {
this.success = success;
this.message = message;
}
}
@AllArgsConstructor 全參構造
@NoArgsConstructor 無參構造,它們都是lombok的注解
Dao層
UserMapper.java
package com.example.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.entities.User;
public interface UserMapper extends BaseMapper<User> {
}
在之前的yml編寫中有這么一句:
# mybatis-plus設置
mybatis-plus:
mapper-locations: classpath:mapper/*.xml #mapper.xml文件位置,如果沒有映射文件,請注釋掉。
接下來,我們創建映射的xml文件
在resource文件夾下,創建mapper文件夾,再創建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.example.mapper.UserMapper">
</mapper>
Service層
首先,創建UserService接口。
package com.example.service;
import com.example.entities.User;
import java.util.List;
public interface UserService {
List<User> findList();
}
再創建它的實現類UserServiceImpl
package com.example.service.impl;
import com.example.entities.User;
import com.example.mapper.UserMapper;
import com.example.service.UserService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
@Resource
private UserMapper userMapper;
@Override
public List<User> findList() {
return userMapper.selectList(null);
}
}
Controller層
創建UserController.java
package com.example.controller;
import com.example.entities.Result;
import com.example.entities.User;
import com.example.service.UserService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.List;
@RestController
public class UserController {
@Resource
private UserService userService;
@GetMapping("user/findList")
public Result findList() {
List<User> list = userService.findList();
if (list != null && list.size() > 0) {
return new Result(true, "查詢成功", list);
} else {
return new Result(false, "查詢失敗");
}
}
}
測試
運行啟動類>Application.java
訪問:http://localhost:8080/user/findList
訪問成功!
使用Mybatis-Plus分頁插件
在pom文件中,導入所需坐標:(這一步,准備中已經做過)
<!--springboot支持的是jpa,mybatisplus自己做了啟動器-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.1.2</version>
</dependency>
第一步:編寫分頁插件配置類
創建MyBatisPlusConfig配置類,內容如下:
package com.example.config;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@EnableTransactionManagement
@Configuration
@MapperScan("com.example.mapper")
public class MyBatisPlusConfig {
/**
* 分頁插件
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
//你的最大單頁限制數量,默認 500 條,小於 0 如 -1 不受限制
//paginationInterceptor.setLimit(2);
return paginationInterceptor;
}
}
第二步:編寫Dao層代碼
修改UserMapper.java ,內容如下:
public interface UserMapper extends BaseMapper<User> {
IPage<User> selectPage(Page page);
}
編寫對應的xml映射文件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.example.mapper.UserMapper">
<select id="selectPage" resultType="com.example.entities.User">
select * FROM user
</select>
</mapper>
編寫一個普通 list 查詢,mybatis-plus 自動替你分頁
加不加where取決於你是否攜帶查詢條件
第三步:調用分頁方法
修改UserService接口:
public interface UserService {
List<User> findList();
IPage<User> selectPage(Page<User> page);
}
修改UserServiceImpl實現類:
@Service
public class UserServiceImpl implements UserService {
@Resource
private UserMapper userMapper;
@Override
public List<User> findList() {
return userMapper.selectList(null);
}
@Override
public IPage<User> selectPage(Page<User> page) {
return userMapper.selectPage(page);
}
}
第四步:編寫Controller
@RestController
public class UserController {
@Resource
private UserService userService;
@GetMapping("user/findList")
public Result findList() {
List<User> list = userService.findList();
if (list != null && list.size() > 0) {
return new Result(true, "查詢成功", list);
} else {
return new Result(false, "查詢失敗");
}
}
@GetMapping("user/selectPage")
public IPage<User> selectPage() {
/**
* Page(current,size)
* current:當前頁,long類型
* size:每頁顯示的數量,long類型
* 可參考其構造方法
*/
IPage<User> userIPage = userService.selectPage(new Page<>(1, 5));
return userIPage;
}
}
測試
運行啟動類>Application.java
訪問:http://localhost:8080/user/findList
使用瀏覽器訪問:
使用postman工具訪問:
可以看到,分頁插件自動幫助我們實現了分頁功能。