MyBatis-Plus (简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。
文档
(目录)
一、引入坐标
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
其他版本 https://mvnrepository.com/artifact/com.baomidou/mybatis-plus-boot-starter
完整配置 pom.xml
<?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 https://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.7.7</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>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-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</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>
<!-- https://mvnrepository.com/artifact/com.baomidou/mybatis-plus-boot-starter -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.2</version>
</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>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
二、配置
1、数据源配置
application.yml
# DataSource Config
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/data?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai
username: root
password: 123456
mybatis-plus:
configuration:
# 开启SQL语句打印
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
global-config:
db-config:
# 自增主键策略
id-type: AUTO
2、分页配置
package com.example.demo.config;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* mp的分页拦截器
*/
@Configuration
public class MybatisPlusConfig {
/**
* 新版mp
**/
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
}
3、创建数据表
在data数据库下创建表tb_user
CREATE TABLE `tb_user` (
`id` int NOT NULL AUTO_INCREMENT COMMENT '主键id',
`name` varchar(20) COMMENT '主键id',
`age` int DEFAULT NULL COMMENT '姓名',
PRIMARY KEY (`id`)
);
三、CURD测试
实体类
package com.example.demo.entity.domain;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
/**
* 数据库实体映射
*/
@Data
@TableName("tb_user")
public class User {
private Long id;
private String name;
private Integer age;
}
Mapper
package com.example.demo.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.demo.entity.domain.User;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface UserMapper extends BaseMapper<User> {
}
IService
package com.example.demo.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.example.demo.entity.domain.User;
public interface UserService extends IService<User> {
}
ServiceImpl
package com.example.demo.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.entity.domain.User;
import com.example.demo.mapper.UserMapper;
import com.example.demo.service.UserService;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl
extends ServiceImpl<UserMapper, User>
implements UserService {
}
测试
package com.example.demo.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.entity.domain.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;
@SpringBootTest
public class UserServiceTest {
@Autowired
private UserService userService;
/**
* 插入数据
*/
@Test
void testSave() {
User user = new User();
user.setName("Tom");
user.setAge(20);
userService.save(user);
// INSERT INTO tb_user ( name, age ) VALUES ( ?, ? )
}
/**
* 字段更新
*/
@Test
void testUpdateById() {
User user = new User();
user.setId(1L);
user.setAge(22);
// 仅更新非空的属性
userService.updateById(user);
// UPDATE tb_user SET age=? WHERE id=?
}
/**
* 部分字段更新
*/
@Test
void testUpdateFieldById() {
LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();
updateWrapper.eq(User::getId, 1);
updateWrapper.set(User::getAge, 30);
userService.update(updateWrapper);
// UPDATE tb_user SET age=? WHERE (id = ?)
}
/**
* 查询单条数据
*/
@Test
void testGetById() {
User user = userService.getById(1L);
// SELECT id,name,age FROM tb_user WHERE id=?
System.out.println(user);
// User(id=1, name=Tom, age=22)
}
/**
* 查询多条数据
*/
@Test
void testSelect() {
LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.gt(User::getAge, 20);
// 2次SQL,一次查总记录数,一次查具体数据
// public Page(long current, long size, boolean searchCount)
Page<User> page = new Page<>(1, 10);
userService.page(page, queryWrapper);
// SELECT COUNT(*) AS total FROM tb_user WHERE (age > ?)
// SELECT id,name,age FROM tb_user WHERE (age > ?) LIMIT ?
long total = page.getTotal();
List<User> records = page.getRecords();
System.out.println(total);
// 1
System.out.println(records);
// [User(id=1, name=Tom, age=22)]
}
}
四、API数据接口
通过对象转换和字段转换,我们能很容易控制输入和输出
Controller
package com.example.demo.controller;
import com.example.demo.entity.domain.User;
import com.example.demo.entity.dto.UserDto;
import com.example.demo.entity.vo.UserVo;
import com.example.demo.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
public class UserController {
@Autowired
private UserService userService;
@PostMapping("/api/user/getUserById")
public UserVo getUserById(@RequestBody UserDto userDto) {
System.out.println(userDto);
User user = userService.getById(userDto.getId());
UserVo userVo = new UserVo();
BeanUtils.copyProperties(user, userVo);
return userVo;
}
}
DTO
package com.example.demo.entity.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
/**
* 接收前端提交的数据
*/
@Data
public class UserDto {
@JsonProperty("user_id")
private Long id;
}
VO
package com.example.demo.entity.vo;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
/**
* 返回前端的数据
*/
@Data
public class UserVo {
@JsonProperty("user_id")
private Long id;
private String name;
@JsonProperty("name_label")
private String nameLabel;
public String getNameLabel() {
return "[" + name + ']';
}
private void setNameLabel() {
}
}
接口请求
POST http://localhost:8080/api/user/getUserById
Content-Type: application/json
{
"user_id": 1
}
返回数据
{
"name": "Tom",
"user_id": 1,
"name_label": "[Tom]"
}
完整代码: https://mouday.github.io/spring-boot-demo/