• mybatis-plus


    1.特征

        无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑

        损耗小:启动即会自动注入基本 CURD,性能基本无损耗,直接面向对象操作

        强大的 CRUD 操作:内置通用 Mapper、通用 Service,仅仅通过少量配置即可实现单表大部分 CRUD 操作,更有强大的条件构造器,满足各类使用需求

        支持 Lambda 形式调用:通过 Lambda 表达式,方便的编写各类查询条件,无需再担心字段写错

        支持主键自动生成:支持多达 4 种主键策略(内含分布式唯一 ID 生成器 - Sequence),可自由配置,完美解决主键问题

        支持 ActiveRecord 模式:支持 ActiveRecord 形式调用,实体类只需继承 Model 类即可进行强大的 CRUD 操作

        支持自定义全局通用操作:支持全局通用方法注入( Write once, use anywhere )

        内置代码生成器:采用代码或者 Maven 插件可快速生成 Mapper 、 Model 、 Service 、 Controller 层代码,支持模板引擎,更有超多自定义配置等您来使用

        内置分页插件:基于 MyBatis 物理分页,开发者无需关心具体操作,配置好插件之后,写分页等同于普通 List 查询

        分页插件支持多种数据库:支持 MySQL、MariaDB、Oracle、DB2、H2、HSQL、SQLite、Postgre、SQLServer 等多种数据库

        内置性能分析插件:可输出 SQL 语句以及其执行时间,建议开发测试时启用该功能,能快速揪出慢查询

        内置全局拦截插件:提供全表 delete 、 update 操作智能分析阻断,也可自定义拦截规则,预防误操作
     

     2.使用流程

    2.1 导入依赖
    1. <dependencies>
    2. <dependency>
    3. <groupId>org.springframework.bootgroupId>
    4. <artifactId>spring-boot-starterartifactId>
    5. dependency>
    6. <dependency>
    7. <groupId>org.springframework.bootgroupId>
    8. <artifactId>spring-boot-starter-testartifactId>
    9. <scope>testscope>
    10. dependency>
    11. <dependency>
    12. <groupId>com.baomidougroupId>
    13. <artifactId>mybatis-plus-boot-starterartifactId>
    14. <version>3.5.1version>
    15. dependency>
    16. <dependency>
    17. <groupId>mysqlgroupId>
    18. <artifactId>mysql-connector-javaartifactId>
    19. dependency>
    20. dependencies>
    2.2 启动类中注入注解

    在spring boot启动类中添加@MapperScan注解,扫描Mapper文件夹:

    1. @SpringBootApplication
    2. @MapperScan("com.wen.mybatis_plus.mapper") //扫描mapper
    3. public class MybatisPlusApplication {
    4. public static void main(String[] args) {
    5. SpringApplication.run(MybatisPlusApplication.class, args);
    6. }
    7. }
    2.3编写mapper包下的接口
    1. @Mapper
    2. public interface UserMapper extends BaseMapper {
    3. }
    2.4开始测试
    1. @SpringBootTest
    2. class MybatisPlusApplicationTests {
    3. //继承了BaseMapper所有的方法,可以编写自己的扩展方法
    4. @Autowired
    5. private UserMapper userMapper;
    6. @Test
    7. public void testSelect(){
    8. System.out.println("--------selectAll method test-------");
    9. //查询全部用户,参数是一个Wrapper,条件构造器,先不使用为null
    10. List userList = userMapper.selectList(null);
    11. userList.forEach(System.out::println);
    12. }

    3.mybatis-plus封装的sql

    1. public interface BaseMapper extends Mapper {
    2. int insert(T entity);
    3. int deleteById(Serializable id);
    4. int deleteByMap(@Param("cm") Map columnMap);
    5. int delete(@Param("ew") Wrapper queryWrapper);
    6. int deleteBatchIds(@Param("coll") Collection idList);
    7. int updateById(@Param("et") T entity);
    8. int update(@Param("et") T entity, @Param("ew") Wrapper updateWrapper);
    9. T selectById(Serializable id);
    10. List selectBatchIds(@Param("coll") Collection idList);
    11. List selectByMap(@Param("cm") Map columnMap);
    12. T selectOne(@Param("ew") Wrapper queryWrapper);
    13. Integer selectCount(@Param("ew") Wrapper queryWrapper);
    14. List selectList(@Param("ew") Wrapper queryWrapper);
    15. List> selectMaps(@Param("ew") Wrapper queryWrapper);
    16. List selectObjs(@Param("ew") Wrapper queryWrapper);
    17. extends IPage> E selectPage(E page, @Param("ew") Wrapper queryWrapper);
    18. extends IPage>> E selectMapsPage(E page, @Param("ew") Wrapper queryWrapper);
    19. }
    20. 3.1各个方法举例
      3.1.1 插入一条记录
      1. User user = new User();
      2. user.setName("John");
      3. user.setAge(30);
      4. int result = baseMapper.insert(user);
      3.1.2 根据主键删除记录
      int result = baseMapper.deleteById(1);
      
      3.1.3 根据列的键值对删除记录
      1. Map columnMap = new HashMap<>();
      2. columnMap.put("age", 30);
      3. int result = baseMapper.deleteByMap(columnMap);
      3.1.4 根据条件删除记录
      1. QueryWrapper queryWrapper = new QueryWrapper<>();
      2. queryWrapper.eq("age", 30);
      3. int result = baseMapper.delete(queryWrapper);
      3.1.5 根据一批主键值删除多条记录
      1. List idList = Arrays.asList(1, 2, 3);
      2. int result = baseMapper.deleteBatchIds(idList);
      3.1.6 根据主键更新记录
      1. User user = new User();
      2. user.setId(1);
      3. user.setName("UpdatedName");
      4. int result = baseMapper.updateById(user);
      3.1.7 根据条件更新记录
      1. UpdateWrapper updateWrapper = new UpdateWrapper<>();
      2. updateWrapper.eq("age", 30);
      3. User user = new User();
      4. user.setName("UpdatedName");
      5. int result = baseMapper.update(user, updateWrapper);
      3.1.8 根据主键查询一条记录
      User user = baseMapper.selectById(1);
      
      3.1.9 根据一批主键值查询多条记录
      1. List idList = Arrays.asList(1, 2, 3);
      2. List userList = baseMapper.selectBatchIds(idList);
      3.1.10 根据列的键值对查询记录
      1. Map columnMap = new HashMap<>();
      2. columnMap.put("age", 30);
      3. List userList = baseMapper.selectByMap(columnMap);
      3.1.11 根据条件查询一条记录
      1. QueryWrapper queryWrapper = new QueryWrapper<>();
      2. queryWrapper.eq("age", 30);
      3. User user = baseMapper.selectOne(queryWrapper);
      3.1.12 根据条件查询记录的数量
      1. QueryWrapper queryWrapper = new QueryWrapper<>();
      2. queryWrapper.eq("age", 30);
      3. Integer count = baseMapper.selectCount(queryWrapper);
      3.1.13 根据条件查询多条记录
      1. QueryWrapper queryWrapper = new QueryWrapper<>();
      2. queryWrapper.eq("age", 30);
      3. List userList = baseMapper.selectList(queryWrapper);
      3.1.14 根据条件查询多条记录,并将结果转换为Map的列表
      1. QueryWrapper queryWrapper = new QueryWrapper<>();
      2. queryWrapper.eq("age", 30);
      3. List> resultMapList = baseMapper.selectMaps(queryWrapper);
      3.1.15 根据条件查询多条记录,并将结果转换为Object的列表
      1. QueryWrapper queryWrapper = new QueryWrapper<>();
      2. queryWrapper.eq("age", 30);
      3. List resultList = baseMapper.selectObjs(queryWrapper);
        3.1.16 分页查询
        1. Page page = new Page<>(1, 10);
        2. QueryWrapper queryWrapper = new QueryWrapper<>();
        3. queryWrapper.eq("age", 30);
        4. IPage userPage = baseMapper.selectPage(page, queryWrapper);
        3.1.17 分页查询并返回Map的列表
        1. Page page = new Page<>(1, 10);
        2. QueryWrapper queryWrapper = new QueryWrapper<>();
        3. queryWrapper.eq("age", 30);
        4. IPage> resultMapPage = baseMapper.selectMapsPage(page, queryWrapper);

        4.LambdaQueryWrapper跟querywrapper的区别是什么?

        1. 使用方式

          • QueryWrapper:在使用 QueryWrapper 构建查询条件时,通常需要传递字符串形式的字段名,如 queryWrapper.eq("name", "John"),其中 "name" 是数据库表中的字段名。这种方式在编码时容易出现拼写错误或者字段名变更导致的问题。

          • LambdaQueryWrapper:与 LambdaQueryWrapper 一起使用时,可以利用 Lambda 表达式,直接引用实体类的属性,如 lambdaQueryWrapper.eq(User::getName, "John")。这种方式在编码时更加类型安全,编译器可以检查属性名的正确性,避免拼写错误或者字段名变更导致的问题。

        2. 类型安全性

          • QueryWrapper:由于 QueryWrapper 使用字符串字段名,因此在编译时不会对字段名进行类型检查,容易在运行时出现错误,特别是在字段名变更或者拼写错误的情况下。

          • LambdaQueryWrapper:使用 Lambda 表达式引用属性名,可以在编译时进行类型检查,因此更加类型安全,可以在编码阶段捕获到错误。

        3. IDE支持

          • LambdaQueryWrapper 更容易受到现代IDE的支持,例如自动补全和重构工具,因为它们可以理解Lambda表达式,而不仅仅是字符串。

        5.queryWrapper的方法

        1. eq(String column, Object value):等于查询条件。

        2. ne(String column, Object value):不等于查询条件。

        3. gt(String column, Object value):大于查询条件。

        4. ge(String column, Object value):大于等于查询条件。

        5. lt(String column, Object value):小于查询条件。

        6. le(String column, Object value):小于等于查询条件。

        7. between(String column, Object val1, Object val2):范围查询条件。

        8. notBetween(String column, Object val1, Object val2):不在范围内的查询条件。

        9. like(String column, Object value):模糊查询条件。

        10. notLike(String column, Object value):不包含查询条件。

        11. likeLeft(String column, Object value):左模糊查询条件。

        12. likeRight(String column, Object value):右模糊查询条件。

        13. isNull(String column):为 null 查询条件。

        14. isNotNull(String column):不为 null 查询条件。

        15. in(String column, Collection values):in 查询条件。

        16. notIn(String column, Collection values):not in 查询条件。

        17. inSql(String column, String inValue):in 查询条件,in 子查询。

        18. notInSql(String column, String inValue):not in 查询条件,not in 子查询。

        19. groupBy(String... columns):分组查询条件。

        20. orderByAsc(String... columns):升序排序查询条件。

        21. orderByDesc(String... columns):降序排序查询条件。

        22. last(String... sql):在 SQL 语句最后添加自定义 SQL 片段。

        23. apply(String applySql, Object... params):动态添加 SQL 片段,可以用于复杂的条件组合。

        24. and():连接多个查询条件,使用 AND 连接。

        25. or():连接多个查询条件,使用 OR 连接。

        26. nested(Consumer> consumer):嵌套查询条件,用于构建复杂的查询逻辑。

        27. exists(String existsSql):exists 子查询条件。

        28. notExists(String notExistsSql):not exists 子查询条件。

        29. select(String... columns):指定查询的字段。

        30. selectExclude(String... excludeColumns):排除不查询的字段。

         6. mybatis-plus分页

        1. @Configuration
        2. @MapperScan("com.xuecheng.content.mapper")
        3. public class MybatisPlusConfig {
        4. /**
        5. * 定义分页拦截器
        6. */
        7. @Bean
        8. public MybatisPlusInterceptor mybatisPlusInterceptor() {
        9. MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        10. interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        11. return interceptor;
        12. }
        13. }

        分页的演示

        1. public PageResult queryCourseBaseList(PageParams pageParams, QueryCourseParamsDto queryCourseParamsDto) {
        2. //构建查询条件对象
        3. LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>();
        4. //构建查询条件,根据课程名称查询
        5. //判断queryCourseParamsDto.getCourseName())是否为空,不为空模糊查询CourseBase中的name,查询关键字是queryCourseParamsDto.getCourseName()
        6. queryWrapper.like(StringUtils.isNotEmpty(queryCourseParamsDto.getCourseName()), CourseBase::getName, queryCourseParamsDto.getCourseName());
        7. //构建查询条件,根据课程审核状态查询
        8. queryWrapper.eq(StringUtils.isNotEmpty(queryCourseParamsDto.getAuditStatus()), CourseBase::getAuditStatus, queryCourseParamsDto.getAuditStatus());
        9. //构建查询条件,根据课程发布状态查询
        10. queryWrapper.eq(StringUtils.isNotEmpty(queryCourseParamsDto.getPublishStatus()), CourseBase::getStatus, queryCourseParamsDto.getPublishStatus());
        11. //分页对象
        12. Page page = new Page<>(pageParams.getPageNo(), pageParams.getPageSize());
        13. // 查询数据内容获得结果
        14. Page pageResult = courseBaseMapper.selectPage(page, queryWrapper);
        15. // 获取数据列表
        16. List list = pageResult.getRecords();
        17. // 获取数据总数
        18. long total = pageResult.getTotal();
        19. // 构建结果集
        20. PageResult courseBasePageResult = new PageResult<>(list, total, pageParams.getPageNo(), pageParams.getPageSize());
        21. return courseBasePageResult;
        22. }

        上述代码pageResult的方法总结

        1. getRecords():获取分页查询的数据记录列表,通常返回一个 List,包含了查询到的课程信息。

        2. getTotal():获取总记录数,返回一个 long 类型的值,表示满足查询条件的总记录数。

        3. getCurrent():获取当前页码,返回一个 long 类型的值,表示当前页的页码。

        4. getSize():获取每页记录数,返回一个 long 类型的值,表示每页显示的记录数。

        5. getPages():获取总页数,返回一个 long 类型的值,表示满足查询条件的总页数。

        6. hasPrevious():判断是否有上一页,返回一个 boolean 类型的值,如果当前页不是第一页,则返回 true,否则返回 false

        7. hasNext():判断是否有下一页,返回一个 boolean 类型的值,如果当前页不是最后一页,则返回 true,否则返回 false

        8. getOrders():获取排序字段信息,返回一个 List,表示按照哪些字段进行排序,以及排序的方式(升序还是降序)。

        9. optimizeCountSql(boolean isCount):设置是否优化总记录数查询的SQL,传入 true 表示进行优化,传入 false 表示不进行优化。

        10. searchCount(boolean searchCount):设置是否查询总记录数,传入 true 表示查询总记录数,传入 false 表示不查询总记录数。

        11. isSearchCount():判断是否查询总记录数,返回一个 boolean 类型的值,如果设置了查询总记录数则返回 true,否则返回 false

        12. getCurrentMap():获取当前分页查询的参数信息,返回一个 Map,包含了当前页码、每页记录数等信息。

        13. optimizePageSize(boolean isOptimize):设置是否优化分页查询的SQL,传入 true 表示进行优化,传入 false 表示不进行优化。

      4. 相关阅读:
        linux系统操作/基本命令/vim/权限修改/用户建立
        OGV内容生产工业化
        升级降级苹果手机iOS系统工具iMazing2024
        Prometheus,Zabbix优缺点分析
        【日常训练】535. TinyURL 的加密与解密
        VEX —— Functions|Nodes
        AudioOptions
        ABB LDGRB-01 3BSE013177R1 数字量输入模块
        大二毕设.3-网盘系统
        《Java并发编程实战》第4章-对象的组合
      5. 原文地址:https://blog.csdn.net/weixin_60934893/article/details/133003319