软件编程
位置:首页>> 软件编程>> java编程>> SpringBoot框架中Mybatis-plus的简单使用操作汇总

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

作者:xsha_h  发布时间:2022-12-17 19:10:53 

标签:SpringBoot,Mybatis-plus,使用

Mybatis-plus

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

配置mysql

在配置文件连接mysql

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使用方式

依赖导入

<!-- 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依赖导入

<!-- lombok用来简化实体类 -->
<dependency>
   <groupId>org.projectlombok</groupId>
   <artifactId>lombok</artifactId>
</dependency>

Mybatis-plus实现简单的CURD操作

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

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

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;
}

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

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类中进行简单的单元测试)

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自动填充策略

主键自动填充

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

时间自动填充

实体类属性添加注解

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

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

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)

  • 在配置类中添加乐观锁插件

@Configuration
@MapperScan("com.xsha.boot.mapper")
public class MyConfig {
   // 乐观锁插件
   @Bean
   public OptimisticLockerInterceptor optimisticLockerInterceptor() {
       return new OptimisticLockerInterceptor();
   }
}

Mybatis-plus查询操作(简单)

// 单个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实现分页操作

在配置类中配置分页插件

// 分页插件
@Bean
public PaginationInterceptor paginationInterceptor() {
   return new PaginationInterceptor();
}

编写分页代码

// 分页查询
@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删除操作(简单)

物理删除

// 单个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注解

@TableLogic
private int delete;

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

// 逻辑删除插件
@Bean
public ISqlInjector sqlInjector() {
   return new LogicSqlInjector();
}

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

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

代码编写

// 逻辑删除
@Test
public void logicDeleteTopic() {
   int row = topicMapper.deleteById(21);
   System.out.println(row);
}

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

性能分析

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

/**
* 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;
}

在配置文件中配置环境

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

Mybatis-plus实现复杂条件查询

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

// 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);
}

来源:https://www.cnblogs.com/aitiknowledge/p/15929246.html

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com