服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - SpringBoot框架中Mybatis-plus的简单使用操作汇总

SpringBoot框架中Mybatis-plus的简单使用操作汇总

2022-07-22 11:48xsha_h Java教程

这篇文章主要介绍了SpringBoot框架中Mybatis-plus的简单使用,本文通过示例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

Mybatis-plus

官网地址:https://baomidou.com/

配置mysql

在配置文件连接mysql

?
1
2
3
4
5
6
7
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/cat_house?serverTimezone=GMT%2B8
spring.datasource.username=username
spring.datasource.password=password
 
# mybatis日志(控制台能显示SQL语句)
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

Mybatis-plus使用方式

依赖导入

?
1
2
3
4
5
6
7
8
9
10
11
<!-- mybatis驱动 -->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.0.5</version>
</dependency>
<!-- 数据库驱动 -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>

lombok依赖导入

?
1
2
3
4
5
<!-- lombok用来简化实体类 -->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
</dependency>

Mybatis-plus实现简单的CURD操作

准备表格(数据库有相应的表格)

准备实体(实体文件夹中有相应的实体类)

?
1
2
3
4
5
6
7
8
9
10
package com.xsha.boot.entity;
import lombok.Data;
@Data
public class Topic {
    private int id;
    private String title;
    private String time;
    private int count;
    private int version;
}

准备映射文件(映射文件夹中有相应的映射接口)

?
1
2
3
4
5
6
7
8
package com.xsha.boot.mapper;
 
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.xsha.boot.entity.Topic;
import org.springframework.stereotype.Repository;
@Repository
public interface TopicMapper extends BaseMapper<Topic> {
}

测试操作(在test类中进行简单的单元测试)

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package com.xsha.boot;
 
import com.xsha.boot.entity.Topic;
import com.xsha.boot.mapper.TopicMapper;
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 MainApplicationTest {
    @Autowired
    // 可在指定的接口上添加注解Repository,就不会爆红了
    private TopicMapper topicMapper;
    // 查询所有数据
    @Test
    public void findAll() {
        List<Topic> topics = topicMapper.selectList(null);
        for (int i = 0; i < topics.size(); i++) {
            System.out.println(topics.get(i));
        }
    }
    // 添加操作
    public void addTopic() {
//        SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
//        Date date = new Date();
        Topic topic = new Topic();
        topic.setTitle("SSM框架整合了哪些主流框架");
        // 时间的添加可以采用mybatis-plus框架实现,可查看Controller中接口实现和实体类属性的注解
//        topic.setTime(ft.format(date));
        int row = topicMapper.insert(topic);
        System.out.println("添加的行数:"+row);
    // 修改操作
    public void updateTopic() {
        topic.setId(20);
        topic.setCount(10);
        int row = topicMapper.updateById(topic);
        System.out.println("修改的行数"+row);
}

Mybatis-plus自动填充策略

主键自动填充

?
1
2
3
4
// 可以在id属性上添加TableId注解可以修改id唯一键值的策略(自动填充),如@TableId(type=IdType.AUTO)
// @TableId(type=IdType.ID_WORKER) 生成19位唯一数字的键值
// @TableId(type=IdType.ID_WORKER_STR) 生成19位唯一字符串的键值
private int id;

时间自动填充

实体类属性添加注解

?
1
2
3
4
5
// 采用mybatis-plus框架的策略自动填充时间
// @TableField(fill=FieldFill.INSERT)  表示自动填充创建时间
// @TableField(fill=FieldFill.INSERT_UPDATE) 表示自动填充更新时间
@TableField(fill = FieldFill.INSERT)
private String time;

Controller类继承接口实现时间自动填充方法

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package com.xsha.boot.controller;
 
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
import java.util.Date;
@Component
public class MyMetaObjectController implements MetaObjectHandler {
    // 使用mybatis-plus实现添加操作,这个方法自动调用
    @Override
    public void insertFill(MetaObject metaObject) {
        SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        Date date = new Date();
        // 第一个参数不是表格的字段名称,而是实体类的属性名称
        this.setFieldValByName("time", ft.format(date), metaObject);
    }
    // 使用mybatis-plus实现更新操作,这个方法自动调用
    public void updateFill(MetaObject metaObject) {
        // 更新时间可根据需求实现
}

乐观锁的具体实现

  • 表格添加字段version,作为乐观锁版本号
  • 对应实体类添加版本号属性,并且在属性上面添加注解Version(baomidou下的Version)
  • 在配置类中添加乐观锁插件
?
1
2
3
4
5
6
7
8
9
@Configuration
@MapperScan("com.xsha.boot.mapper")
public class MyConfig {
    // 乐观锁插件
    @Bean
    public OptimisticLockerInterceptor optimisticLockerInterceptor() {
        return new OptimisticLockerInterceptor();
    }
}

Mybatis-plus查询操作(简单)

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// 单个id查询
@Test
public void selectTopic() {
    Topic topic = topicMapper.selectById(20);
    System.out.println(topic);
}
 
// 多个id批量查询
@Test
public void selectTopics() {
    List<Topic> topics = topicMapper.selectBatchIds(Arrays.asList(1, 2, 3, 4));
    for (int i = 0; i < topics.size(); i++) {
        System.out.println(topics.get(i));
    }
}

Mybatis-plus实现分页操作

在配置类中配置分页插件

?
1
2
3
4
5
// 分页插件
@Bean
public PaginationInterceptor paginationInterceptor() {
    return new PaginationInterceptor();
}

编写分页代码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// 分页查询
@Test
public void selectByPage() {
    // 1.创建page对象,传递当前页和每页记录数的两个参数
    Page<Topic> page = new Page<>(1, 3);
    // 2.调用mybatis-plus分页查询的方法,把分页所有的数据封装到page对象里面,第二个参数是条件
    topicMapper.selectPage(page, null);
    // 3.通过page对象获取分页数据
    System.out.println(page.getCurrent());  // 当前页
    System.out.println(page.getRecords());  // 每页数据list集合
    System.out.println(page.getSize());  // 每页显示记录数
    System.out.println(page.getTotal());  // 总记录数
    System.out.println(page.getPages());  // 总页数
    System.out.println(page.hasNext());  // 是否有下一页
    System.out.println(page.hasPrevious());  // 是否有上一页
}

Mybatis-plus删除操作(简单)

物理删除

?
1
2
3
4
5
6
7
8
9
10
11
12
13
// 单个id删除
   @Test
   public void deleteTopic() {
       int row = topicMapper.deleteById(20);
       System.out.println(row);
   }
   
   // 多个id批量删除
   @Test
   public void deleteTopics() {
       int rows = topicMapper.deleteBatchIds(Arrays.asList(1, 2, 3, 4));
       System.out.println(rows);
   }

逻辑删除

表格中添加标志位字段,供逻辑删除使用

表格字段设置默认值,就不能使用mybatis-plus的自动填充使用mybatis-plus的自动填充

使用mybatis-plus的自动填充时,在实体类属性上添加TableLogic注解

?
1
2
@TableLogic
private int delete;

在配置类中配置逻辑删除插件

?
1
2
3
4
5
// 逻辑删除插件
@Bean
public ISqlInjector sqlInjector() {
    return new LogicSqlInjector();
}

在配置文件中添加逻辑删除与否的默认值(可有可无)

?
1
2
3
# 逻辑删除与否的默认值
mybatis-plus.global-config.db-config.logic-delete-value=1
mybatis-plus.global-config.db-config.logic-not-delete-value=0

代码编写

?
1
2
3
4
5
6
// 逻辑删除
@Test
public void logicDeleteTopic() {
    int row = topicMapper.deleteById(21);
    System.out.println(row);
}

注意:采用mybatis-plus的逻辑删除方式时,之后查询数据时就不会包括逻辑删除的数据

性能分析

在配置类中添加性能分析插件

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/**
 * SQL执行性能分析插件
 * 开发环境使用,线上不推荐。maxTime指的是sql最大执行时长
 *
 * 三种环境:dev开发环境、test测试环境、prod生成环境
 * @return
 */
@Bean
@Profile({"dev", "test"})   // 设置dev,test的环境开启
public PerformanceInterceptor performanceInterceptor() {
    PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
    performanceInterceptor.setMaxTime(100); // 数值单位为毫秒ms
    performanceInterceptor.setFormat(true);
    return performanceInterceptor;
}

在配置文件中配置环境

?
1
2
# 环境设置:dev  test  prod
spring.profiles.active=dev

Mybatis-plus实现复杂条件查询

使用QueryWrapper类对象构造条件(还有其他的)

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// mybatis-plus实现复杂查询
@Test
public void querySelect() {
    // 1.创建QueryWrapper对象
    QueryWrapper<Topic> queryWrapper = new QueryWrapper<>();
    // 2.通过QueryWrapper设置条件
    // ge(>=)、gt(>)、le(<=)、lt(<)
    queryWrapper.ge("count", 3);
    List<Topic> topics1 = topicMapper.selectList(queryWrapper);
    System.out.println("FIRST");
    System.out.println(topics1);
 
    // eq(==)、ne(!=)
    queryWrapper.ne("deleted", 0);
    List<Topic> topics2 = topicMapper.selectList(queryWrapper);
    System.out.println("SECOND");
    System.out.println(topics2);
    // between(在···和···之间)
    queryWrapper.between("time", "2021-10-12 07:05:29.546779", "2021-10-27 15:02:09.458571");
    List<Topic> topics3 = topicMapper.selectList(queryWrapper);
    System.out.println("THIRD");
    System.out.println(topics3);
    // like(模糊查询)
    queryWrapper.like("title", "SSM");
    List<Topic> topics4 = topicMapper.selectList(queryWrapper);
    System.out.println("FORTH");
    System.out.println(topics4);
    // 排序 orderByDesc   orderByAsc
    queryWrapper.orderByDesc("count");
    List<Topic> topics5 = topicMapper.selectList(queryWrapper);
    System.out.println("FIFTH");
    System.out.println(topics5);
    // 指定要查询的列 last拼接sql语句
    queryWrapper.select("id", "title", "count");
    queryWrapper.last("limit 2");
    List<Topic> topics6 = topicMapper.selectList(queryWrapper);
    System.out.println("SIXTH");
    System.out.println(topics6);
}

到此这篇关于SpringBoot框架中Mybatis-plus的简单使用的文章就介绍到这了,更多相关SpringBoot Mybatis-plus使用内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://www.cnblogs.com/aitiknowledge/p/15929246.html

延伸 · 阅读

精彩推荐