SpringBoot整合mybatis-plus入门教程

时间:2022-10-07 10:19:55 类型:JAVA
字号:    

Mybatis-plus的介绍及优缺点,这里不再详细说明,需要的朋友到官网支详细了解

下面就用一个springboot项目mybatis-plus 的基础操作

第一步:数据库准备

CREATE TABLE `data0917`.`student`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(30) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `sex` char(1) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '男',
  `blood` varchar(2) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '血型',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

第二步:核心依赖

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.5.1</version>
</dependency>

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

  这些是核心依赖,用到了mysql驱动、lombok。集成mybatis-plus要把mybatis、mybatis-spring去掉,避免冲突;lombok是一个工具,添加了这个依赖,就可以使用它的简化功能,最常用的用法就是在实体类中使用它的@Data注解,这样实体类就不用写set、get、toString等方法了。

第三步:application.yml配置

mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
    #开启sql日志
    map-underscore-to-camel-case: true
    # 该配置就是将带有下划线的表字段映射为驼峰格式的实体类属性
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/data0917?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=UTF-8
    username: root
    password: root

第四步:实体类Student.java

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.Data;

@Data
public class Student {
    @TableId(value = "id", type = IdType.AUTO)//指定自增策略
    private Integer id;
    private String name;
    private String sex;
    private String blood;
}

第五步:StudentMapper.java

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.springbootmybatisplus.entity.Student;
import org.apache.ibatis.annotations.Mapper;

@Mapper
//表明这是一个Mapper,也可以在启动类上加上包扫描
//Mapper 继承该接口后,无需编写 mapper.xml 文件,即可获得CRUD功能
public interface StudentMapper  extends BaseMapper<Student> {
}

  这样就完成了mybatis-plus与springboot的整合。把mybatis和mybatis-spring依赖换成mybatis-plus的依赖,最后mapper继承BaseMapper即可。

第六步:Mybatis分页插件配置

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MyBatisPlusPager {
    /**
     * 分页插件
     *
     * @return 分页插件的实例
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        //指定数据库类型是 MySQL
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }
}

第七步:StudentService.java

import com.example.springbootmybatisplus.entity.Student;
import com.example.springbootmybatisplus.mapper.StudentMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class StudentService {
    @Autowired
    private StudentMapper studentMapper;
    //查询全部
    public List<Student> selectAll() {
        return studentMapper.selectList(null);
    }

    //添加一条数据
    public int add(Student student) {
        return studentMapper.insert(student);
    }

    public Student queryById(Student student) {
        return studentMapper.selectById(student.getId());
    }
    //多条件判断判断查询 及 分页
        //当姓名,性别,血型不为空时, 进行条件查询
        public Page<Student> queryWhere(Student student,Page studentPage){
            QueryWrapper<Student> wrapper = new QueryWrapper<>();
            wrapper.like("".equals(student.getName()) == false && student.getName() != null, "name",student.getName())
                    .eq("".equals(student.getSex()) == false && student.getSex() != null, "sex",student.getSex())
                    .eq("".equals(student.getBlood()) == false && student.getBlood() != null, "blood",student.getBlood());
            return studentMapper.selectPage(studentPage,wrapper);
        }
}

第八步:测试类

import com.example.springbootmybatisplus.entity.Student;
import com.example.springbootmybatisplus.service.StudentService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
public class StudentCURDTest {
    @Autowired
    private StudentService studentService;

    @Test
    public void queryAll() {
        studentService.selectAll().forEach(System.out::println);
    }

    @Test
    public void addOne(){
        Student student = new Student();
        student.setName("小小雨");
        student.setSex("男");
        student.setBlood("A");
        System.out.println(studentService.add(student));
    }
    @Test void queryOne(){
        Student student = new Student();
        student.setId(1);
        System.out.println(studentService.queryById(student));
    }
    @Test void queryWhere(){
            Page<Student> studentPage = new Page<Student>(1L, 2L);
            Student student = new Student();
            student.setName("小");
            //student.setBlood("A");
            Page<Student> studentPage1 =studentService.queryWhere(student,studentPage);
            System.out.println("pages"+ studentPage1.getPages());
            System.out.println("total:"+studentPage1.getTotal());
            System.out.println("size:"+studentPage1.getSize());
            studentPage1.getRecords().forEach(System.out::println);
        }
}

Mybatis-plus之IService的使用(以上面的内容为基础), 简单列具两个实例

第一步:创建StuService.java接口, 继承IService

import com.baomidou.mybatisplus.extension.service.IService;
import com.example.springbootmybatisplus.entity.Student;

public interface StuService extends IService<Student> {
}

第二步: 定义实现类StuServiceImpl.java

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.springbootmybatisplus.entity.Student;
import com.example.springbootmybatisplus.mapper.StudentMapper;
import org.springframework.stereotype.Service;

@Service
public class StuServiceImpl extends ServiceImpl<StudentMapper, Student> implements StuService{
}

第三步:测试调用

@Test void iServiceSaveTest(){
    Student student = new Student();
    student.setName("小小雨");
    student.setSex("男");
    student.setBlood("A");
    System.out.println(stuService.save(student));
}

//IPage分页及多条件查询
@Test void iServiceIPageTest(){
    IPage<Student> studentPage = new Page<>(1l,2l);

    Student student = new Student();
    student.setName("小小雨");
    student.setSex("男");
    student.setBlood("A");
    
    QueryWrapper<Student> wrapper = new QueryWrapper<>();
    wrapper.like("".equals(student.getName()) == false && student.getName() != null, "name",student.getName())
            .eq("".equals(student.getSex()) == false && student.getSex() != null, "sex",student.getSex())
            .eq("".equals(student.getBlood()) == false && student.getBlood() != null, "blood",student.getBlood());

    IPage<Student> studentPage1 =stuService.page(studentPage,wrapper);
    System.out.println("pages"+ studentPage1.getPages());
    System.out.println("total:"+studentPage1.getTotal());
    System.out.println("size:"+studentPage1.getSize());
    studentPage1.getRecords().forEach(System.out::println);
}


<