您的位置:首页 > 其它

Mybatis-plus入门教程

2021-11-05 21:20 10 查看 https://www.cnblogs.com/javamm

环境搭建

SpringBoot+Mybatis-Plus

  1. 引入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">
<parent>
<artifactId>lagou-study</artifactId>
<groupId>com.mmc</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>

<artifactId>mybatis-plus</artifactId>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>2.1.2.RELEASE</version>
<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-test</artifactId>
<version>2.1.2.RELEASE</version>
<scope>test</scope>
</dependency>

<!--简化代码的⼯具包-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.22</version>
</dependency>
<!--mybatis-plus的springboot⽀持-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.1.1</version>
</dependency>
<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.13</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>2.0.0-alpha0</version>
</dependency>

</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.1.2.RELEASE</version>
</plugin>
</plugins>
</build>
</project>
  1. application.properties文件
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true&useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=0490218292
  1. log4j.properties
log4j.rootLogger=DEBUG,A1
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=[%t] [%c]-[%p] %m%n
  1. 编写实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName("user")
public class User {

private Integer id;

private String name;
}
  1. 编写Mapper
public interface UserMapper extends BaseMapper<User> {
}
  1. 测试
@SpringBootTest
@RunWith(SpringRunner.class)
public class UserMapperTest {

@Autowired
private UserMapper userMapper;

@Test
public void testSelect(){
List<User> users = userMapper.selectList(null);
System.out.println(users);
}
}

基本使用

下面会根据如下要点讲解mybatis-plus的基本功能

  • 实体类注解
  • 分页
  • 基本配置
  • 性能分析插件、乐观锁等插件
  • 自动填充属性值
  • SQL注入器
  • 逻辑删除
  • MybatisX插件

实体类注解

@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName("user")
public class User {

//id类型子增长
@TableId(type = IdType.AUTO)
private Integer id;

@TableField(value = "name")
private String userName;

private Integer age;

//不查询该字段
@TableField(select = false)
private Date createTime;
}

分页插件

配置:

@Configuration
@MapperScan("com.mmc.mybatisPlus.mapper") //设置mapper接⼝的扫描包
public class MybatisPlusConfig {
/**
* 分⻚插件
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
}

测试代码:

@Test
public void testPage(){
Page<User> page=new Page<>(1,3);
IPage<User> userIPage = userMapper.selectPage(page,null);
System.err.println(userIPage.getRecords());
}

基本配置

#指定配置文件位置
mybatis-plus.config-location = classpath:mybatis-config.xml
#指定mapper的文件位置
mybatis-plus.mapper-locations = classpath*:mybatis/*.xml
#指定别名包扫描路径,配置后可直接使用类名,而不用全类名
mybatis-plus.type-aliases-package = com.mmc.mybatisPlus.bean
#关闭⾃动驼峰映射,该参数不能和mybatis-plus.config-location同时存在
mybatis-plus.configuration.map-underscore-to-camel-case=false
#全局地开启或关闭配置⽂件中的所有映射器已经配置的任何缓存,默认为 true。
mybatis-plus.configuration.cache-enabled=false

#全局配置表名前缀
mybatis-plus.global-config.db-config.table-prefix=tb_

插件使用

  1. 基础使用
@Component
@Intercepts({
@Signature(
type= Executor.class,
method = "query",
args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}
)})
public class MyInterceptor implements Interceptor {

@Override
public Object intercept(Invocation invocation) throws Throwable {
System.out.println("拦截excecutor");
//拦截方法,具体业务逻辑编写的位置
return invocation.proceed();
}

@Override
public Object plugin(Object o) {
//创建target对象的代理对象,⽬的是将当前拦截器加⼊到该对象中
return Plugin.wrap(o,this);
}

@Override
public void setProperties(Properties properties) {

}
}
  1. 性能分析插件

用于输出每条SQL语句及其执行时间,可以设置最大执行时间,超过时间会抛出异常。

@Bean
public PerformanceInterceptor performanceInterceptor(){
PerformanceInterceptor performanceInterceptor = new
PerformanceInterceptor();
performanceInterceptor.setMaxTime(100);
performanceInterceptor.setFormat(true);
return performanceInterceptor;
}
  1. 乐观锁插件
@Bean
public OptimisticLockerInterceptor optimisticLockerInterceptor() {
return new OptimisticLockerInterceptor();
}

实体类上加上@version注解

@Version
private Integer version;

自动填充功能

  1. 给要填充的字段加注解
@TableField(fill = FieldFill.INSERT)
private Date createTime;

填充策略有多种:

public enum FieldFill {

/**
* 默认不处理
*/
DEFAULT,
/**
* 插⼊时填充字段
*/
INSERT,
/**
* 更新时填充字段
*/
UPDATE,
/**
* 插⼊和更新时填充字段
*/
INSERT_UPDATE

}

编写MyMetaObjectHandler

@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

@Override
public void insertFill(MetaObject metaObject) {
Object createTime = getFieldValByName("createTime", metaObject);
if(createTime==null){
setFieldValByName("createTime",new Date(),metaObject);
}
}

@Override
public void updateFill(MetaObject metaObject) {

}
}

SQL注入器

在Mytabis-Plus中,通过AbstractSqlInjector将BaseMapper中的方法注入到Mybatis容器中,这样它的方法才能被正常执行。那么我们如果需要扩展BaseMapper中的方法,该怎么实现呢?

  1. 编写一个MybaseMapper继承BaseMapper
public interface MyBaseMapper<T> extends BaseMapper<T> {
List<T> findAll();
}
  1. 给对应的要扩展的方法编写方法类
public class FindAll extends AbstractMethod {

@Override
public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
String sqlMethod="findAll";
String sql="select * from "+tableInfo.getTableName();
SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, modelClass);
return this.addSelectMappedStatement(mapperClass,sqlMethod,sqlSource,modelClass,tableInfo);
}
}
  1. 注入到容器
@Component
public class MySqlInjector extends DefaultSqlInjector {

@Override
public List<AbstractMethod> getMethodList() {
List<AbstractMethod> methodList = super.getMethodList();
methodList.add(new FindAll());

return methodList;
}
}

逻辑删除

  1. 实体类加注解
@TableLogic
private Integer deleted;
  1. 配置删除属性值
# 逻辑已删除值(默认为 1)
mybatis-plus.global-config.db-config.logic-delete-value=1
# 逻辑未删除值(默认为 0)
mybatis-plus.global-config.db-config.logic-not-delete-value=0
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: