mybatis-plus专题(一)增删改查,条件构造器

Springboot版本:2.1.7.RELEASE
mybatis-plus版本:3.3.1

废话不多说了,开干吧。

1.pom.xml

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.3.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.10</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
    </dependencies>

2.application-yaml配置

mybatis-plus:
  mapper-locations: classpath:mybatis/mapper/*.xml
  type-aliases-package: com.demo.pojo.*
  global-config:
    banner: false
    db-config:
      id-type: auto
    #主键类型  0:"数据库ID自增", 1:"用户输入ID",2:"全局唯一ID (数字类型唯一ID)", 3:"全局唯一ID UUID";
    id-type: 0
    #字段策略 0:"忽略判断",1:"非 NULL 判断"),2:"非空判断"
    field-strategy: 2
    #驼峰下划线转换
    db-column-underline: false
    #刷新mapper 调试神器
    refresh-mapper: true
    #数据库大写下划线转换
    #capital-mode: true
    #序列接口实现类配置,不在推荐使用此方式进行配置,请使用自定义bean注入
    key-generator: com.baomidou.mybatisplus.incrementer.H2KeyGenerator
    #逻辑删除配置(下面3个配置)
    logic-delete-value: 0
    logic-not-delete-value: 1
    #自定义sql注入器,不在推荐使用此方式进行配置,请使用自定义bean注入
    #    sql-injector: com.example.mybatisplus.mapper.LogicSqlInjector
    #自定义填充策略接口实现,不在推荐使用此方式进行配置,请使用自定义bean注入
    #    meta-object-handler: com.baomidou.springboot.MyMetaObjectHandler
    #自定义SQL注入器
    #sql-injector: com.baomidou.springboot.xxx
    # SQL 解析缓存,开启后多租户 @SqlParser 注解生效
    sql-parser-cache: true
  configuration:
    map-underscore-to-camel-case: true
    cache-enabled: false
    config-location: classpath:mybatis/mybatis-config.xml

3.编写映射实体类

package com.example.mp.mpdemo.entity;

import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;

import java.util.Date;

/**
 * @author Honey
 * @Date 2021/9/24
 * @Description
 */
@TableName(value = "student")
@Data
public class Student {

    //自增主键,多种IdType,可以自行点进去查看,有中文注释
    @TableId(type = IdType.AUTO)
    private Long id;

    //如果数据库的字段名称与实体变量名不一致,使用注解进行指定
    @TableField(value = "student_name")
    private String stuName;

    //不写TableField的时候,默认就是驼峰命名,会映射到数据库stu_sex
    private String stuSex;

    private Integer status;

    //新增时自动填充,在一个配置类里进行字段填充。
    @TableField(fill = FieldFill.INSERT, value = "create_time")
    private Date createTime;

    //创建人
    @TableField(fill = FieldFill.INSERT)
    private Long createBy;

    //编辑时自动填充,在一个配置类里进行字段填充。
    @TableField(fill = FieldFill.UPDATE, value = "update_time")
    private Date updateTime;

    //编辑自动填充
    @TableField(fill = FieldFill.UPDATE)
    private Long updateBy;

    //逻辑删除字段,0删除,1为删除,数值配置在application.yaml里面
    //加了此注解表示是逻辑删除字段,sql会自动拼接上 where del_flag = 1 ,无需手动处理。
    //如果某些sql需要查询已删除的,则需要自己按照mybatis的方式在xml里写sql
    //mybatis-plus理念,如果你需要查询已删除的数据,就不要使用这个东西了,用另外的字段比如status去处理。
    @TableLogic
    private Integer delFlag;

}

3.mapper接口,继承了BaseMapper之后就有了基本的crud的接口了

package com.example.mp.mpdemo.mapper;

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

/**
 * @author Honey
 * @Date 2021/9/24
 * @Description
 */
@Mapper
public interface StudentMapper extends BaseMapper<Student> {

    /**
     * 继承了BaseMapper之后就有了基本的crud的接口了
     */
}

4.Service接口

package com.example.mp.mpdemo.service;

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

/**
 * @author Honey
 * @Date 2021/9/24
 * @Description
 */
public interface StudentService extends IService<Student> {
    /**
     * 继承IService接口,内部封装了mapper的基本CRUD,还多了批量新增,批量删除的方法。
     */
}

5. CRUD

分页配置,如果不配置这个Bean会导致分页无效

@Configuration
public class MybatisPlusConfig {

    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        //查询的最大条数,防止OOM
        paginationInterceptor.setLimit(5000);
        return paginationInterceptor;
    }
}

CRUD代码

package com.example.mp.mpdemo;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.mp.mpdemo.entity.Student;
import com.example.mp.mpdemo.mapper.StudentMapper;
import com.example.mp.mpdemo.service.StudentService;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;

import javax.annotation.Resource;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@SpringBootTest
class MpDemoApplicationTests {

    /**
     * 一般都是注入service,这里test演示都注入
     */
    @Resource
    private StudentMapper studentMapper;

    /**
     * 一般都是注入service,这里test演示都注入
     */
    @Resource
    private StudentService studentService;

    @Test
    void contextLoads() {
        //***********************新增*****************************
        /**
         * 新增单条
         */
        Student student = new Student();
        student.setStatus(1);
        student.setStuName("张三");
        int insert = studentMapper.insert(student);
        String msg = insert > 0 ? "新增成功" : "新增失败";
        /**
         * 新增单条
         */
        Student student2 = new Student();
        student.setStatus(2);
        student.setStuName("张三2");
        boolean save = studentService.save(student);
        String msg2 = save ? "新增成功" : "新增失败";
        /**
         * 批量新增
         * 内部还是单条循环新增
         */
        List<Student> list = new ArrayList<>();
        list.add(student);
        list.add(student2);
        boolean b = studentService.saveBatch(list);
        String msg3 = b ? "新增成功" : "新增失败";

        //**********************编辑******************************
        /**
         * 根据主键编辑
         * 动态编辑
         */
        Student stu = new Student();
        stu.setId(1L);
        stu.setStuName("李四");
        studentMapper.updateById(stu);
        studentService.updateById(stu);

        /**
         * 把名字为张三的状态都改成2
         */
        LambdaUpdateWrapper<Student> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(Student::getStuName, "张三");
        Student s = new Student();
        s.setStatus(2);
        studentMapper.update(s, lambdaUpdateWrapper);
        studentService.update(s, lambdaUpdateWrapper);

        //************************删除**********************************
        studentMapper.deleteById(1);
        studentService.removeById(1);
        //批量删除
        studentService.removeByIds(Arrays.asList(new int[]{1,2,3}));
        //条件删除
        QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("student_name", "张三");
        studentService.remove(queryWrapper);

        //*********************查询***********************************

        /**
         * 根据主键查询
         */
        Student student1 = studentMapper.selectById(1L);
        Student byId = studentService.getById(1L);

        /**
         * 根据主键批量查询
         */
        List<Student> list1 = studentMapper.selectBatchIds(Arrays.asList(new int[]{1, 2, 3}));
        List<Student> list2 = studentService.listByIds(Arrays.asList(new int[]{1, 2, 3}));

        /**
         * 查询状态等于1的
         */
        QueryWrapper<Student> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("status", 1);
        List<Student> list3 = studentMapper.selectList(queryWrapper);
        List<Student> list4 = studentService.list(queryWrapper);
        //一般都是使用LambdaQueryWrapper
        LambdaUpdateWrapper<Student> studentLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        studentLambdaUpdateWrapper.eq(Student::getStatus, 1);
        List<Student> list5 = studentMapper.selectList(studentLambdaUpdateWrapper);
        List<Student> list6 = studentService.list(studentLambdaUpdateWrapper);

        /**
         * 查这个sql
         * select id,status from student where (stu_name like '%张三%' or true_name like '%张三%' )
         *  and status = 1 and create_time >= 2021-09-24 15:33:33 and create_time <= 2021-09...
         *  group by status order by id desc limit 50;
         */
        QueryWrapper<Student> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.select("id,status");
        LambdaQueryWrapper<Student> lambda = queryWrapper2.lambda();
        //like默认是两边模糊查询。如果需要单边可以有likeLeft和likeRight
        lambda.and(q -> q.like(Student::getStuName, "张三").or().like(Student::getTrueName, "张三"));
        lambda.eq(Student::getStatus, 1);
        lambda.ge(Student::getCreateTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").parse("2021-09-24 15:33:33"));
        lambda.le(Student::getCreateTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").parse("2021-09-30 15:33:33"));
        lambda.groupBy(Student::getStatus);
        lambda.orderByDesc(Student::getId);
        lambda.last("limit 50");
        List<Student> list7 = studentMapper.selectList(lambda);

        /**
         * 动态sql
         */
        String name = null;
        LambdaQueryWrapper<Student> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(StringUtils.isNotBlank(name), Student::getStuName, name);
        List<Student> list8 = studentMapper.selectList(lambdaQueryWrapper);

        /**
         * 分页查询
         * 需要配置分页插件,否则分页无效
         */
        Page<Student> studentPage = studentMapper.selectPage(new Page<>(1, 10), lambdaQueryWrapper);
        List<Student> records = studentPage.getRecords();
        long total = studentPage.getTotal();

        /**
         * 统计函数
         */
        QueryWrapper<Student> studentQueryWrapper = new QueryWrapper<>();
        studentQueryWrapper.select("sum(status) as status");
        //使用selectOne的时候,如果查询结果出现了多条,会报错,所以要注意,结果一定不能大于1
        Student student3 = studentMapper.selectOne(studentQueryWrapper);
        //求和
        Integer status = student3.getStatus();

        /**
         * 重复使用条件构造器
         */
        LambdaQueryWrapper<Student> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
        for (Student student4 : list) {
            //清空条件
            lambdaQueryWrapper1.clear();
            lambdaQueryWrapper1.like(Student::getStuName, student4.getStuName());
            List<Student> list9 = studentMapper.selectList(lambdaQueryWrapper);
        }
    }

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值