SpringBoot数据交互

Mybatis-Plus

Mybatis-plus (以下简称MP) 是一款基于Mybatis开发的一款拓展框架

image

Mybatis框架的优缺点:

  • 优点
    • 灵活性强,可以自定义sql语句,任何复杂情况都能够去解决
    • 兼容性好,因为是基于JDBC驱动的,只要是JDBC支持的数据库他都可以支持
  • 缺点
    • 编写复杂,首先需要部分配置和大量的Sql编写,没有简单的类似JPA的方法式使用

那MP的诞生就是为了去解决Mybatis的复杂性的问题

该框架是无侵入式的,对原生Mybatis工程不会有影响,且可以提供更简单方便的代码操作

简单使用Mybatis-Plus

配置

首先导入依赖

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-spring-boot3-starter</artifactId>
    <version>3.5.9</version>
</dependency>

配置数据源

server:
  port: 8080
spring:
  datasource:
    url: jdbc:mysql://192.168.11.11:3307/test
    username: root
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.Driver

实体类

创建一个实体类

@AllArgsConstructor
@NoArgsConstructor
@Data
@TableName("student") //表示该实体对应表名为 student
public class Student {
    @TableId(type = IdType.AUTO) //设定该值为主键且自增
    Integer id;

    @TableField("name") //设定该值对应字段为 name
    String name;

    @TableField("password") //设定该值对应字段为password
    String password;
}

创建Mapper类

@Mapper //和原生Mybatis一样 声明该类为Mapper类
public interface UserMapper extends BaseMapper<Student> { //继承BaseMapper 泛型内为该Mapper所操作的类型
    
    //可以使用继承于 BaseMapper中提供的一系列方法,也可以使用Mybatis原有的方式进行操作
    @Select("select * from student where id=#{id}")
    Student MyselectById(Integer id);
}

使用

@SpringBootTest
class SpringTestApplicationTests {


    @Resource
    private UserMapper userMapper; // 自动注入userMapper

    @Test
    void contextLoads() {
        Student student = new Student();
        student.setName("xufan");
        student.setPassword("123456");

//        int insert = userMapper.insert(student);
        Student student1 = userMapper.MyselectById(1);
        System.out.println(student1);
    }

}

BaseMapper中提供了大量基础方法,简化流程

image

条件构造器

image

例如我现在想在该表结构中查询出name为mianju的字段,因为sql语句是这样写的

select * from student 
where name = 'mianju'

现在我们有个where来进行自定义条件的筛选,所以我们需要构造我们自定义的条件

@Resource
private UserMapper userMapper;

@Test
void contextLoads() {
    // 创建一个条件构造器 也就是需要的条件往里面塞就行
    QueryWrapper<Student> studentQueryWrapper = new QueryWrapper<>();

    studentQueryWrapper
        //选择要查询的字段,为空则为所有字段 也就是 *
            .select("id","name") 
        
        // 可以在第一个参数添加Boolean值 是触发器,为True则触发添加该条件
            .eq("name","mianju");

    System.out.println(userMapper.selectOne(studentQueryWrapper));
}

我们开启sql日志打印

mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

可以看到

image

语句就是我们上面所要求的,那多条件的话只需要再添加几条就可以

// 我想查询id < 2 且 name = xufan 的字段
@Resource
private UserMapper userMapper;

@Test
void contextLoads() {
    // 创建一个条件构造器 也就是需要的条件往里面塞就行
    QueryWrapper<Student> studentQueryWrapper = new QueryWrapper<>();

    studentQueryWrapper
            .select()
        // id 小于 2
            .lt("id", 2)
        // 且 name = xufan
            .eq("name","xufan");

    System.out.println(userMapper.selectOne(studentQueryWrapper));
}

image

批处理

在程序中最忌讳的就是 ==使用for循环去执行sql 一个循环一个sql语句的执行==

这样对性能来说是巨大的压力的挑战,我们通过MP可以直接将需要的合并到一个sql语句来执行

例如:我需要查找id为 [1,2,4] 的字段

@Test
void contextLoads() {
    // 将id为1,2,4的记录查询出来
    List<Student> students = userMapper.selectByIds(List.of(1, 2, 4));
    System.out.println(students);
}

image

那这样就可以把多个Sql简单快速的合并为一个sql

快速分页

MP可以快速实现分页功能,首先我们需要配置一下

@Configuration
public class MybatisConfiguration {
    @Bean
    public MybatisPlusInterceptor paginationInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
      	//添加分页拦截器到MybatisPlusInterceptor中
        //在MP3.5.9 版本之后 该插件模块被分离出来 需要在pom中导包
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }
}

如果mp版本大于3.5.9 需要在maven中再导入插件包

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-jsqlparser</artifactId>
    <version>3.5.9</version>
</dependency>

分页代码:

@Test
    void contextLoads() {
        // 我们将数据分为2页 每页3条数据,并获取第一页的数据
        // 1为当前第1页 3为每页3条数据
        // 不进行条件限制
        Page<Student> studentPage = userMapper.selectPage(Page.of(1, 3), null);
        List<Student> records = studentPage.getRecords();
        System.out.println(records);

        // 倒叙查询则需要加条件限制
        QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
        // 设置以id为倒叙来查询
        queryWrapper.orderByDesc("id");
        
        Page<Student> studentPage1 = userMapper.selectPage(Page.of(1, 3), queryWrapper);
        List<Student> records1 = studentPage1.getRecords();
        System.out.println(records1);
    }

接口预设操作

MP提供了Mapper层的快捷调用已经很方便了,但是业务中我们使用service层其实大部分也是调用底层方法

Mp也给我们提供了 Service层 的快捷调用

定义Service接口

@Service
public interface UserService extends IService<Student> { // 继承 Mybatis-plus 提供的类
    // 还可以自定义需要的方法
    Student myGetUserById(Integer id);
}

创建Service接口的实现类

// 需要继承ServiceImpl<要操作的Mapper,要操作的对象> 并实现自己的 UserService
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, Student> implements UserService {
    // 重写刚刚自定义的方法
    @Override
    public Student myGetUserById(Integer id) {
        System.out.println("这是我自定义的实现方法,传入的参数为:" + id);
        return new Student();
    }
}

在controller层自动装配Bean

@Resource
private UserService userServiceImpl;

调用

@Test
void serviceTest() 
    // 使用自定义的方法
    Student student = userServiceImpl.myGetUserById(123);
    System.out.println(student);
}

结果:

image

MP也提供了大量的方法:

image

文章作者: 面具
版权声明: 本站所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 MianJu —— 这只是一个 Title 而已~
springboot mybatis-plus java springboot java mysql mybatis
喜欢就支持一下吧