美文网首页
24.MyBatisPlus

24.MyBatisPlus

作者: 星野君 | 来源:发表于2022-05-05 14:59 被阅读0次

一、快速入门

  1. 导入坐标
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.1</version>
        </dependency>
  1. dao继承BaseMappler
package com.ylf.dao;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.ylf.doamin.Student;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface StudentDao extends BaseMapper<Student> {}

  1. CRUD
package com.ylf;

import com.ylf.dao.StudentDao;
import com.ylf.doamin.Student;
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
class Mybatispuls01ApplicationTests {
  @Autowired private StudentDao studentDao;

  @Test
  void add() {
    final Student student = new Student();
    student.setName("张三");
    student.setChinese(50);
    student.setEnglish(60);
    student.setMath(90);
    studentDao.insert(student);
  }

  @Test
  void update() {
    final Student student = new Student();
    student.setId(2);
    student.setMath(90);
    studentDao.updateById(student);
  }

  @Test
  void delete() {
    studentDao.deleteById(1);
  }

  @Test
  void selectById() {
    Student student = studentDao.selectById(1);
    System.out.println(student);
  }

  @Test
  void selectAll() {
    List<Student> st = studentDao.selectList(null);
    System.out.println(st);
  }
}

二、lombok

  • 这个插件可以简化pojo层,不用再重复写set、get方法
  1. 导入坐标
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.24</version>
            <scope>provided</scope>
        </dependency>
  1. 实体类
package com.ylf.doamin;

import lombok.Data;

@Data
public class Student {
  private Integer id;
  private String name;
  private Integer chinese;
  private Integer english;
  private Integer math;
}

@Data包含了@Setter@Getter@ToString等
不包含@NoArgsConstructor @AllArgsConstructor

三、分页

  1. 创建配置类com.ylf.config.MyBatisPlusConfig
package com.ylf.config;

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 MyBatisPlusConfig {
  @Bean
  public MybatisPlusInterceptor mybatisPlusInterceptor() {
    // 1.定义拦截器
    final MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
    // 2. 添加具体的拦截器
    mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor());
    return mybatisPlusInterceptor;
  }
}

  1. 分页
  @Test
  void testPage() {
    final Page<Student> studentPage = new Page(1, 2);
    studentDao.selectPage(studentPage, null);
    System.out.println("当前页码:" + studentPage.getCurrent());
    System.out.println("每页显示多少:" + studentPage.getSize());
    System.out.println("总页数:" + studentPage.getPages());
    System.out.println("一共多少数据:" + studentPage.getTotal());
    System.out.println("数据:" + studentPage.getRecords());
  }

四、条件查询

  @Test
  void select() {
    LambdaQueryWrapper<Student> lqw = new LambdaQueryWrapper();
    // 小于80并且大于20
    lqw.lt(Student::getChinese, 80).gt(Student::getEnglish, 20);
    // 小于80或者大于20
    // lqw.lt(Student::getChinese, 80).or().gt(Student::getEnglish, 20);
    List<Student> st = studentDao.selectList(lqw);
    System.out.println(st);
  }
  • 查询空判定
lqw.lt(null != 分数1, Student::getChinese, 分数1).gt(null != 分数2, Student::getEnglish, 分数2);
  • 查询指定字段
  @Test
  void select() {
    LambdaQueryWrapper<Student> lqw = new LambdaQueryWrapper();
    lqw.select(Student::getId, Student::getName);
    List<Student> st = studentDao.selectList(lqw);
    System.out.println(st);
  }
  • 统计查询
  @Test
  void select() {
    QueryWrapper<Student> lqw = new QueryWrapper();
    lqw.select("count(*) as count");
    List<Map<String, Object>> st = studentDao.selectMaps(lqw);
    System.out.println(st);
  }
  • 分组
  @Test
  void select() {
    QueryWrapper<Student> lqw = new QueryWrapper();
    lqw.select("count(*) as count, name");
    lqw.groupBy("name");
    List<Map<String, Object>> st = studentDao.selectMaps(lqw);
    System.out.println(st);
  }
  • 模糊查询
  @Test
  void select() {
    LambdaQueryWrapper<Student> lqw = new LambdaQueryWrapper();
    lqw.like(Student::getName, "欧阳");
    //    lqw.likeLeft(Student::getName, "张");
    //    lqw.likeRight(Student::getName, "云");
    //    Student st = studentDao.selectOne(lqw);
    //    System.out.println(st);
    List<Student> st = studentDao.selectList(lqw);
    System.out.println(st);
  }

五、字段映射

import lombok.Data;

/**
 * @author 余龙飞
 * @version 1.0
 */
@Data
// 和数据库表做映射
@TableName("tb_student")
public class Student {
  private Integer id;
  private String name;
  // 映射数据库字段名,并且不参与查询
  @TableField(value = "chi", select = false)
  private Integer chinese;

  private Integer english;
  private Integer math;
  // 数据库不存在的字段,不参与查询
  @TableField(exist = false)
  private Integer online;
}

六、id生成策略

@Data
public class Student {
  // 根据数据库主键自增
  @TableId(type = IdType.AUTO)
  // 雪花算法id
  //@TableId(type = IdType.ASSIGN_ID)
  // 用户自己输入的id
  //@TableId(type = IdType.INPUT)
  // uuid算法生成的id
  //@TableId(type = IdType.ASSIGN_UUID)
  private Integer id;
}
  • 全局设定
    application.yml
mybatis-plus:
  global-config:
    db-config:
      id-type: auto
      table-prefix: tb_

七、逻辑删除

  • 实体类字段上加上@TableLogic注解
@TableLogic(value = "0", delval = "1")
private Integer deleted;
  • 或者使用全局配置
mybatis-plus:
  global-config:
    db-config:
      logic-delete-field: deleted# 全局逻辑删除的实体字段名
      logic-delete-value: 1 # 逻辑已删除值(默认为 1)
      logic-not-delete-value: 0 # 逻辑未删除值(默认为 0)

八、乐观锁

  1. 配置
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
    MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
    interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
    return interceptor;
}
  1. 在实体类的字段上加上@Version注解
@Version
private Integer version;

九、代码生成器

  • MBG代码生成器是基于xml文件进行代码生成,可以生成实体类、Mapper接口、Mapper映射文件
    • MyBatisPlus代码生成器基于java代码来完成,可以生成实体类、Mapper接口、Mapper映射文件、Service层、Controller层。
  1. 引入坐标
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.4.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity-engine-core</artifactId>
            <version>2.3</version>
        </dependency>
  1. 创建Generator
    @Test
    public void testGenerator(){

        //1、全局配置
        GlobalConfig globalConfig = new GlobalConfig();
        globalConfig.setActiveRecord(true)  //是否支持AR模式
                .setAuthor("Jian")
                .setOutputDir("D:\\Java\\workspace_idea\\MybatisPlus\\src\\main\\java")     //生成路径
                .setFileOverride(true)      //是否支持文件覆盖
                .setIdType(IdType.AUTO)     //主键策略
                .setServiceName("%sService")        //设置生成的service接口名字首字符是否为I
                .setBaseResultMap(true)             //设置是否支持映射结果集
                .setBaseColumnList(true);           //设置是否支持生成数据库列名集合


        //2、数据源配置
        DataSourceConfig dataSourceConfig = new DataSourceConfig();
        dataSourceConfig.setDbType(DbType.MYSQL)    //设置数据库类型
                .setDriverName("com.mysql.jdbc.Driver")
                .setUrl("jdbc:mysql://localhost:3306/mp")
                .setUsername("root")
                .setPassword("root");

        //3、策略配置
        StrategyConfig strategyConfig = new StrategyConfig();
        strategyConfig.setCapitalMode(true)         //全局大写命名
                .setNaming(NamingStrategy.underline_to_camel)       //数据库表映射到实体的命名规则,下划线-->驼峰命名
                .setTablePrefix("tbl_")             //指定表名前缀
                .setInclude("tbl_employee");        //生成的表

        //4、包名策略配置
        PackageConfig packageConfig = new PackageConfig();
        packageConfig.setParent("mpGenerator")
                .setMapper("mapper")            //指定Mapper接口包名
                .setService("service")          //指定service层包名
                .setController("controller")    //指定Controller层包名
                .setEntity("bean")              //指定bean包名
                .setXml("mapper");              //xml映射文件放在mapper包下

        //5、整合配置
        AutoGenerator autoGenerator = new AutoGenerator();
        autoGenerator.setGlobalConfig(globalConfig)
                .setDataSource(dataSourceConfig)
                .setStrategy(strategyConfig)
                .setPackageInfo(packageConfig);
        
        //6、执行
        autoGenerator.execute();
        

    }

代码生成器(旧) | MyBatis-Plus (baomidou.com)

相关文章

  • 24.MyBatisPlus

    一、快速入门 导入坐标 dao继承BaseMappler CRUD 二、lombok 这个插件可以简化pojo层,...

网友评论

      本文标题:24.MyBatisPlus

      本文链接:https://www.haomeiwen.com/subject/ygzeyrtx.html