参考文档:https://www.jianshu.com/p/12ec123d20e8
https://www.jianshu.com/p/12ec123d20e8
导入依赖包
<dependencies>
<!-- springweb -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.3.1.RELEASE</version>
</dependency>
<!-- mysql驱动依赖 -->
<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>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- MbatisPlus -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.1.2</version>
</dependency>
<!-- 阿里巴巴Druid数据源 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.0</version>
</dependency>
</dependencies>
项目结构
springboot配置文件
spring:
datasource:
# 设置数据源类型为阿里巴巴Druid数据源
type: com.alibaba.druid.pool.DruidDataSource
# 数据库驱动
driver-class-name: com.mysql.cj.jdbc.Driver
# mysql数据库连接地址,時區為本地時區,支持Unicode編碼,使用UTF-8編碼,serverTimezone=UTC解决时区报错
url: jdbc:mysql://39.97.68.32:3306/mybatisplus?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
# mysql用户名
username: root
password: root123
# 數據源初始連接數
initialSize: 5
# 最小空閒數
minIdle: 5
# 最大活躍數
maxActive: 20
# 配置連接超時時間
maxWait: 60000
timeBetweenEvictionRunsMills: 60000
minEvictableIdleTimeMills: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
# 配置后,druid控制台才能監控sql語句執行
# 配置监控统计拦截的filters, stat:监控统计 log4j:日志记录 wall:防御sql注入
filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
userGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMilils=500
mybatis:
type-aliases-package: com.liwi.springbootmybatisplus.pojo
mapper-locations: classpath:mapper/*.xml
创建Mapper映射文件
使用mybatisplus框架时必须继承内部提供的 BaseMapper类,其中范型为与数据库进行映射的Pojo对象. mybatisplus提供了许多简单的增删改查操作.
UserMapper.class
package com.liwi.springbootmybatisplus.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.liwi.springbootmybatisplus.pojo.User;
import org.springframework.stereotype.Repository;
//
@Repository
public interface UserMapper extends BaseMapper<User> {
}
测试对user表插入一条数据
test.class
package com.liwi.springbootmybatisplus;
import com.liwi.springbootmybatisplus.mapper.OrderMapper;
import com.liwi.springbootmybatisplus.mapper.UserMapper;
import com.liwi.springbootmybatisplus.pojo.Order;
import com.liwi.springbootmybatisplus.pojo.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.Date;
@SpringBootTest
class SpringbootMybatisplusApplicationTests {
@Autowired
UserMapper userMapper;
@Test
void contextLoads() {
User user = new User();
user.setName("lindan");
user.setAge(32);
user.setCreate_time(new Date());
user.setEmail("784415702@qq.com");
userMapper.insert(user);
}
}
常用注解
MyBatisPlus提供了一些注解供我们在实体类和表信息出现不对应的时候使用。通过使用注解完成逻辑上匹配。
注解名称 | 说明 |
---|---|
@TableName | 实体类的类名和数据库表名不一致时 |
@TableId | 实体类的主键名称和表中主键名称不一致 |
@TableField | 实体类中的成员名称和表中字段名称不一致 |
演示
package com.liwi.springbootmybatisplus.pojo;
import com.baomidou.mybatisplus.annotation.TableName;
import java.util.Date;
// 将该对象与t_user表进行映射
@TableName("t_user")
public class User {
private Long id;
private String name;
private int age;
private String email;
private Long manager_id;
private Date create_time;
}
主键策略
// @TableId(value=,type=)
package com.baomidou.mybatisplus.annotation;
public enum IdType {
AUTO(0), //自增(数据库也要自增)
NONE(1), //未设置主键时
INPUT(2), //手动输入
ID_WORKER(3), //默认额全局唯一ID
UUID(4), //默认额全局唯一ID
ID_WORKER_STR(5); //ID_WORKER的字符串表示法
private final int key;
private IdType(int key) {
this.key = key;
}
public int getKey() {
return this.key;
}
}
配置一个乐观锁
当每次对数据进行更新的时候,会比对version值是否与缓存中的version一致,一致则更新
1.在Pojo对象中加入version属性,添加@Version注解
2.数据库对应关系表添加version字段
3.创建MybatisPlusCnfig.class配置类
MybatisPlusCnfig.class
package com.liwi.springbootmybatisplus.config;
import com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@MapperScan("com.liwi.springbootmybatisplus.mapper")
@EnableTransactionManagement
@Configuration
public class MybatisPlusConfig {
// 注册乐观锁插件
@Bean
public OptimisticLockerInterceptor optimisticLockerInterceptor(){
return new OptimisticLockerInterceptor();
}
}
测试代码
@Test
void testOptimistic(){
User user = userMapper.selectById(1);
System.out.println(user);
user.setCreate_time(new Date());
userMapper.updateById(user);
}
结果sql中带上了version字段进行条件判断
分页
- sql语句中limit实现
- 使用pageHelper插件进行实现
- MybatisPlus自带的分页插件(需要配置拦截器实现)
package com.liwi.springbootmybatisplus.config;
import com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor;
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;
@MapperScan("com.liwi.springbootmybatisplus.mapper")
@EnableTransactionManagement
@Configuration
public class MybatisPlusConfig {
// 分页插件
@Bean
public PaginationInterceptor paginationInterceptor(){
return new PaginationInterceptor();
}
}
测试代码
// 使用分页插件进行分页查询
@Test
void testSelectPage(){
// 从第0条数据开始,每页5条数据
Page page = new Page(0,5);
userMapper.selectPage(page,null);
List<User> users = page.getRecords();
users.forEach(System.out::println);
page.getRecords().forEach(System.out::println);
}
逻辑删除
物理删除: 从数据库直接删除数据
逻辑删除: 设置一个字段deleted =0 ,当进行删除时对修改deleted = 1,这样可以让管理员能查看到被删除的记录
- 在数据库与Pojo对象添加deleted字段,pojo加上@TableLogic注解
- 在mybatisplusConfig配置文件中添加插件
- application.yaml配置deleted值 或 注解配置mybatisplus版本须大于3.2
application.yaml
mybatis-plus:
global-config:
db-config:
# 删除表示1
logic-delete-value: 1
# 未删除时表示0
logic-not-delete-value: 0
@TableLogic(value = "1",delval = "0") //逻辑删除
private Integer showStatus;
插件导入
package com.liwi.springbootmybatisplus.config;
import com.baomidou.mybatisplus.core.injector.ISqlInjector;
import com.baomidou.mybatisplus.extension.injector.LogicSqlInjector;
import com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor;
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;
@MapperScan("com.liwi.springbootmybatisplus.mapper")
@EnableTransactionManagement
@Configuration
public class MybatisPlusConfig {
// 删除插件(过时了)
@Bean
public ISqlInjector sqlInjector(){
return new LogicSqlInjector();
}
}
测试
@Test
void testDelete(){
// 删除id=4的几率
userMapper.deleteById(4);
}
结果:执行deleteById方法,deleted值被修改(并没真正删除记录)
注意:在执行selectById(id)方法时,会自动过滤deleted值为1 的记录
性能检测
用于检测sql执行时的性能如何
- 添加插件
package com.liwi.springbootmybatisplus.config;
import com.baomidou.mybatisplus.core.injector.ISqlInjector;
import com.baomidou.mybatisplus.extension.injector.LogicSqlInjector;
import com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.PerformanceInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@MapperScan("com.liwi.springbootmybatisplus.mapper")
@EnableTransactionManagement
@Configuration
public class MybatisPlusConfig {
// 性能检测插件
@Bean
@Profile({"dev"})
public PerformanceInterceptor performanceInterceptor(){
PerformanceInterceptor p = new PerformanceInterceptor();
p.setMaxTime(1); // 设置sql执行最大时间ms,超出时间不执行sql报错
p.setFormat(true); // 是否格式化sql输出
return p;
}
}