• SpringBoot学习笔记(十七:MyBatis-Plus )


    @



    一、MyBatis-Plus简介

    MyBatis-Plus (简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。

    在这里插入图片描述

    MyBatis-Plus具有如下特性:

    • 无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑
    • 损耗小:启动即会自动注入基本 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 操作智能分析阻断,也可自定义拦截规则,预防误操作

    官网地址:https://baomidou.com/


    二、基本用法

    1、准备数据

    我们这里使用MySQL数据库,先准备好相关数据

    表结构:其中种类和产品是一对多的关系
    在这里插入图片描述

    建表语句:

    DROP TABLE IF EXISTS `category`;
    CREATE TABLE `category`  (
      `cid` int(11) NOT NULL AUTO_INCREMENT,
      `category_name` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
      PRIMARY KEY (`id`) USING BTREE
    ) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '种类表' ROW_FORMAT = Dynamic;
    
    -- ----------------------------
    -- Table structure for product
    -- ----------------------------
    DROP TABLE IF EXISTS `product`;
    CREATE TABLE `product`  (
      `pid` int(11) NOT NULL AUTO_INCREMENT,
      `product_name` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
      `category_id` int(11) NOT NULL,
      `price` decimal(10, 2) NULL DEFAULT NULL,
      PRIMARY KEY (`id`) USING BTREE
    ) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
    
    
    

    2、引入依赖

    通过开发工具创建一个SpringBoot项目(版本为2.4.0),引入以下依赖:

            <!--mybatis-plus依赖-->
            <dependency>
                <groupId>com.baomidou</groupId>
                <artifactId>mybatis-plus-boot-starter</artifactId>
                <version>3.4.1</version>
            </dependency>
            <!--mysql驱动-->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <scope>runtime</scope>
            </dependency>
    

    2、配置

    在配置文件里写入相关配置:

    spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
    spring.datasource.url=jdbc:mysql://localhost:3306/mp-demo?characterEncoding=utf-8&allowMultiQueries=true&serverTimezone=GMT%2B8
    spring.datasource.username=root
    spring.datasource.password=root
    

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

    @SpringBootApplication
    @MapperScan("cn.fighter3.mapper")
    public class SpringbootMybatisPlusApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(SpringbootMybatisPlusApplication.class, args);
        }
    
    }
    

    3、代码

    • 实体类
    /**
     * @Author 三分恶
     * @Date 2020/11/14
     * @Description 产品实体类
     */
    @TableName(value = "product")
    public class Product {
        @TableId(type = IdType.AUTO)
        private Long pid;
        private String productName;
        private Long categoryId;
        private Double price;
        //省略getter、setter
    }
    
    • Mapper接口:继承BaseMapper即可
    /**
     * @Author 三分恶
     * @Date 2020/11/14
     * @Description
     */
    public interface ProductMapper extends BaseMapper<Product> {
    }
    

    4、测试

    • 添加测试类
    @SpringBootTest
    class SpringbootMybatisPlusApplicationTests {
    }
    
    • 插入
        @Test
        @DisplayName("插入数据")
        public void testInsert(){
            Product product=new Product();
            product.setProductName("小米10");
            product.setCategoryId(1l);
            product.setPrice(3020.56);
            Integer id=productMapper.insert(product);
            System.out.println(id);
        }
    
    • 根据id查找
        @Test
        @DisplayName("根据id查找")
        public void testSelectById(){
            Product product=productMapper.selectById(1l);
            System.out.println(product.toString());
        }
    
    • 查找所有
        @Test
        @DisplayName("查找所有")
        public void testSelect(){
           List productList=productMapper.selectObjs(null);
            System.out.println(productList);
        }
    
    • 更新
        @Test
        @DisplayName("更新")
        public void testUpdate(){
            Product product=new Product();
            product.setPid(1l);
            product.setPrice(3688.00);
            productMapper.updateById(product);
        }
    
    • 删除
        @Test
        @DisplayName("删除")
        public void testDelete(){
            productMapper.deleteById(1l);
        }
    

    三、自定义SQL

    使用MyBatis的主要原因是因为MyBatis的灵活,mp既然是只对MyBatis增强,那么自然也是支持以Mybatis的方式自定义sql的。

    • 修改pom.xml,在 <build>中添加:
        <build>
            <resources>
                <resource>
                    <directory>src/main/java</directory>
                    <includes>
                        <include>**/*.xml</include>
                    </includes>
                    <filtering>true</filtering>
                </resource>
                <resource>
                    <directory>src/main/resources</directory>
                </resource>
            </resources>
        </build>
    
    • 配置文件:添加mapper扫描路径及实体类别名包
    mybatis.mapper-locations=classpath:cn/fighter3/mapper/*.xml
    mybatis.type-aliases-package=cn.fighter3.model
    

    1、自定义批量插入

    批量插入是比较常用的插入,BaseMapper中并没有默认实现,在com.baomidou.mybatisplus.service.IService中虽然实现了,但是是一个循环的插入。

    所以用Mybatis的方式自定义一个:

    • 在ProductMapper同级路径下新建ProductMapper:
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="cn.fighter3.mapper.ProductMapper">
    
    </mapper>
    
    • 在接口里定义批量插入方法
    public interface ProductMapper extends BaseMapper<Product> {
        void batchInsert(@Param("productList") List<Product> productList);
    }
    
    • 编写批量插入xml脚本
        <insert id="batchInsert">
            insert into product (product_name,category_id,price)
            values
            <foreach collection="productList" item="product" separator=",">
                (#{product.productName},#{product.categoryId},#{product.price})
            </foreach>
        </insert>
    
    • 测试
        @Test
        public void testBatchInsert(){
            List<Product> productList=new ArrayList<>();
            productList.add(new Product("小米10",1l,3020.56));
            productList.add(new Product("Apple iPhone 11",1l,4999.00));
            productList.add(new Product("Redmi 8A",1l,699.00));
            productList.add(new Product("华为 HUAWEI nova 5z",1l,1599.00));
            productList.add(new Product("OPPO A52",1l,1399.00));
            productMapper.batchInsert(productList);
        }
    

    2、自定义查询

    基本的Mybatis方式的查询这里就不再展示了,参照Mybatis的即可。

    MP提供了一种比较方便的查询参数返回和查询条件参数传入的机制。


    2.1、自定义返回结果

    Mybatis Plus接口里定义的查询是可以直接以map的形式返回。

    • 定义:定义了一个方法,返回用的是map
        /**
         * 返回带分类的产品
         * @return
         */
        List<Map> selectProductWithCategory();
    
    • 查询脚本:查询字段有pid、product_name、category_name、price
        <select id="selectProductWithCategory" resultType="map">
          select p.pid,p.product_name,c.category_name,p.price from product p left  join  category c on  p.category_id=c.cid
       </select>
    
    • 测试:
        @Test
        @DisplayName("自定义返回结果")
        public void testsSlectProductWithCategory(){
            List<Map> productList=productMapper.selectProductWithCategory();
            productList.stream().forEach(item->{
                System.out.println(item.toString());
            });
        }
    
    • 结果:

    在这里插入图片描述


    2.2、自定义查询条件参数

    除了返回结果可以使用map,查询用的参数同样可以用map来传入。

    • 定义:
        List<Map> selectProductWithCategoryByMap(Map<String,Object> map);
    
    • 查询脚本:
        <select id="selectProductWithCategoryByMap" resultType="map" parameterType="map">
          select p.pid,p.product_name,c.category_name,p.price from product p left  join  category c on  p.category_id=c.cid
          <where>
              <if test="categoryId !=null and categoryId !=''">
                  and p.category_id=#{categoryId}
              </if>
              <if test="pid !=null and pid !=''">
                  and p.pid=#{pid}
              </if>
          </where>
       </select>
    
    • 测试:
        @Test
        @DisplayName("自定义返回结果有入参")
        public void testSelectProductWithCategoryByMap(){
            Map<String,Object> params=new HashMap<>(4);
            params.put("categoryId",1l);
            params.put("pid",5);
            List<Map> productList=productMapper.selectProductWithCategoryByMap(params);
            productList.stream().forEach(item->{
                System.out.println(item.toString());
            });
        }
    
    • 结果:
      在这里插入图片描述

    2.3、map转驼峰

    上面查询结果可以看到,返回的确实是map,没有问题,但java类中的驼峰没有转回来呀,这样就不友好了。

    只需要一个配置就能解决这个问题。

    创建 MybatisPlusConfig.java 配置类,添加上下面配置即可实现map转驼峰功能。

    /**
     * @Author 三分恶
     * @Date 2020/11/16
     * @Description
     */
    @Configuration
    @MapperScan("cn.fighter.mapper")
    public class MybatisPlusConfig {
        @Bean("mybatisSqlSession")
        public SqlSessionFactory sqlSessionFactory(@Qualifier("dataSource") DataSource dataSource) throws Exception {
            MybatisSqlSessionFactoryBean sqlSessionFactory = new MybatisSqlSessionFactoryBean();
            MybatisConfiguration configuration = new MybatisConfiguration();
            configuration.setDefaultScriptingLanguage(MybatisXMLLanguageDriver.class);
            configuration.setJdbcTypeForNull(JdbcType.NULL);
            //*注册Map 下划线转驼峰*
            configuration.setObjectWrapperFactory(new MybatisMapWrapperFactory());
    
            // 添加数据源
            sqlSessionFactory.setDataSource(dataSource);
    
            sqlSessionFactory.setConfiguration(configuration);
    
            return sqlSessionFactory.getObject();
        }
    }
    

    再次运行之前的单元测试,结果:

    在这里插入图片描述

    OK,下划线已经转驼峰了。


    3、自定义一对多查询

    在实际应用中我们常常需要用到级联查询等查询,可以采用Mybatis的方式来实现。


    3.1、 Category相关

    category和product是一对多的关系,我们这里先把category表相关的基本实体、接口等编写出来。

    • Category.java
    /**
     * @Author 三分恶
     * @Date 2020/11/15
     * @Description
     */
    @TableName(value = "category")
    public class Category {
        @TableId(type = IdType.AUTO)
        private Long id;
        private String categoryName;
        private List<Product> productList;
        //省略getter、setter等
    }
    
    • CategoryMapper.java
    /**
     * @Author 三分恶
     * @Date 2020/11/15
     * @Description
     */
    public interface CategoryMapper extends BaseMapper<Category> {
    }
    
    • CategoryMapper.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="cn.fighter3.mapper.CategoryMapper">
    
    </mapper>
    

    直接向数据库中插入数据:

    INSERT into category(category_name) VALUE ('手机');
    

    3.2、自定义返回结果

    自定义返回结果map:

        <!--自定义返回列-->
        <resultMap id="categoryAndProduct" type="cn.fighter3.model.Category">
            <id column="cid" property="cid" />
            <result column="category_name" property="categoryName" />
            <!--一对多关系-->
            <!-- property: 指的是集合属性的值, ofType:指的是集合中元素的类型 -->
            <collection property="productList" ofType="cn.fighter3.model.Product">
                <id column="pid" property="pid" />
                <result column="product_name" property="productName" />
                <result column="category_id" property="categoryId" />
                <result column="price" property="price" />
            </collection>
        </resultMap>
    

    3.3、自定义一对多查询

    • 先定义方法
    public interface CategoryMapper extends BaseMapper<Category> {
        List<Category> selectCategoryAndProduct(Long id);
    }
    
    • 查询脚本
        <!--查询分类下的产品-->
        <select id="selectCategoryAndProduct" resultMap="categoryAndProduct" parameterType="java.lang.Long">
           select c.*,p.* from category c left join product p on c.cid=p.category_id
           <if test="id !=null and id !=''">
               where c.cid=#{id}
           </if>
        </select>
    
    • 测试
        @Test
        public void testSelectCategoryAndProduct(){
            List<Category> categoryList=categoryMapper.selectCategoryAndProduct(null);
            categoryList.stream().forEach(i->{
               i.getProductList().stream().forEach(product -> System.out.println(product.getProductName()));
            });
        }
    

    Mybatis方式的一对多查询就完成了。多对一、多对多查询这里就不再展示,参照Mybatis即可。


    4、 分页查询

    mp的分页查询有两种方式,BaseMapper分页和自定义查询分页。

    4.1、BaseMapper分页

    直接调用方法即可:

        @Test
        @DisplayName("分页查询")
        public void testSelectPage(){
            QueryWrapper<Product> wrapper = new QueryWrapper<>();
            IPage<Product> productIPage=new Page<>(0, 3);
            productIPage=productMapper.selectPage(productIPage,wrapper);
            System.out.println(productIPage.getRecords().toString());
        }
    

    4.2、自定义分页查询

    • 在前面写的MybatisPlusConfig.java 配置类sqlSessionFactory方法中添加分页插件:
            //添加分页插件
            PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
            sqlSessionFactory.setPlugins(new Interceptor[]{paginationInterceptor});
    
    • 定义方法
        IPage<Map> selectProductMapWithPage(IPage iPage);
    
    • 查询脚本
        <select id="selectProductMapWithPage" resultType="map">
          select p.pid,p.product_name,c.category_name,p.price from product p left  join  category c on  p.category_id=c.cid
       </select>
    
    • 测试
        @Test
        @DisplayName("自定义分页查询")
        public void testSelectProductMapWithPage(){
            Integer pageNo=0;
            Integer pageSize=2;
            IPage<Map> iPage = new Page<>(pageNo, pageSize);
            iPage=productMapper.selectProductMapWithPage(iPage);
            iPage.getRecords().stream().forEach(item->{
                System.out.println(item.toString());
            });
        }
    
    • 结果
      在这里插入图片描述

    这里有几点需要注意:

    1. 在xml文件里写的sql语句不要在最后带上;,因为有些分页查询会自动拼上 limit 0, 10; 这样的sql语句,如果你在定义sql的时候已经加上了 ;,调用这个查询的时候就会报错了
    2. 往xml文件里的查询方法里传参数要带上 @Param("") 注解,这样mybatis才认,否则会报错
    3. 分页中传的pageNo可以从0或者1开始,查询出的结果是一样的,这一点不像jpa里必须是从0开始才是第一页

    四、代码生成器

    相信用过Mybatis的开发应该都用过Mybatis Gernerator,这种代码自动生成插件大大减少了我等crud仔的重复工作。MP同样提供了代码生成器的功能。

    AutoGenerator 是 MyBatis-Plus 的代码生成器,通过 AutoGenerator 可以快速生成 Entity、Mapper、Mapper XML、Service、Controller 等各个模块的代码,极大的提升了开发效率。


    1、引入依赖

    在原来项目的基础上,添加如下依赖。

    • MyBatis-Plus 从 3.0.3 之后移除了代码生成器与模板引擎的默认依赖,需要手动添加相关依赖:
            <!--代码生成器依赖-->
            <dependency>
                <groupId>com.baomidou</groupId>
                <artifactId>mybatis-plus-generator</artifactId>
                <version>3.4.1</version>
            </dependency>
    
    • 添加 模板引擎 依赖,MyBatis-Plus 支持 Velocity(默认)、Freemarker、Beetl,用户可以选择自己熟悉的模板引擎,如果都不满足要求,可以采用自定义模板引擎。
      Velocity(默认):
            <!--模板引擎依赖,即使不需要生成模板,也需要引入-->
            <dependency>
                <groupId>org.apache.velocity</groupId>
                <artifactId>velocity-engine-core</artifactId>
                <version>2.2</version>
            </dependency>
    
    • 其它依赖
            <!--会生成Controller层,所以引入-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
            <!--代码生成器中用到了工具类-->
            <dependency>
                <groupId>org.apache.commons</groupId>
                <artifactId>commons-lang3</artifactId>
                <version>3.11</version>
            </dependency>
    

    2、代码生成

    下面这个类是代码生成的一个示例。因为在前后端分离的趋势下,实际上我们已经很少用模板引擎了,所以这里没有做模板引擎生成的相关配置。

    public class MySQLCodeGenerator {
    
        /**
         * <p>
         * 读取控制台内容
         * </p>
         */
        public static String scanner(String tip) {
            Scanner scanner = new Scanner(System.in);
            StringBuilder help = new StringBuilder();
            help.append("请输入" + tip + ":");
            System.out.println(help.toString());
            if (scanner.hasNext()) {
                String ipt = scanner.next();
                if (StringUtils.isNotBlank(ipt)) {
                    return ipt;
                }
            }
            throw new MybatisPlusException("请输入正确的" + tip + "!");
        }
    
        public static void main(String[] args) {
            // 代码生成器
            AutoGenerator mpg = new AutoGenerator();
    
            // 全局配置
            GlobalConfig gc = new GlobalConfig();
            String projectPath = "D:\IdeaProjects\dairly-learn\springboot-mybatis-plus";
            //输出目录
            gc.setOutputDir(projectPath + "/src/main/java");
            gc.setAuthor("三分恶");
            gc.setOpen(false);
            // gc.setSwagger2(true); 实体属性 Swagger2 注解
            mpg.setGlobalConfig(gc);
    
            // 数据源配置
            DataSourceConfig dsc = new DataSourceConfig();
            dsc.setUrl("jdbc:mysql://localhost:3306/mp-demo?characterEncoding=utf-8&allowMultiQueries=true&serverTimezone=GMT%2B8");
            dsc.setDriverName("com.mysql.cj.jdbc.Driver");
            dsc.setUsername("root");
            dsc.setPassword("root");
            mpg.setDataSource(dsc);
    
            //包配置
            PackageConfig pc = new PackageConfig();
            pc.setModuleName(scanner("模块名"));
            pc.setParent("cn.fighter3");
            mpg.setPackageInfo(pc);
    
            // 自定义配置
            InjectionConfig cfg = new InjectionConfig() {
                @Override
                public void initMap() {
                    // to do nothing
                }
            };
    
    
            ///策略配置
            StrategyConfig strategy = new StrategyConfig();
            strategy.setNaming(NamingStrategy.underline_to_camel);
            strategy.setColumnNaming(NamingStrategy.underline_to_camel);
            //strategy.setSuperEntityClass("你自己的父类实体,没有就不用设置!");
            strategy.setEntityLombokModel(false);
            strategy.setRestControllerStyle(true);
            // 公共父类
            //strategy.setSuperControllerClass("你自己的父类控制器,没有就不用设置!");
            // 写于父类中的公共字段
            //strategy.setSuperEntityColumns("id");
            strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
            strategy.setControllerMappingHyphenStyle(true);
            strategy.setTablePrefix(pc.getModuleName() + "_");
            mpg.setStrategy(strategy);
            mpg.execute();
        }
    
    }
    

    • 运行该类,运行结果如下

    在这里插入图片描述

    • 生成的代码如下:

    在这里插入图片描述

    已经生成了基本的三层结构。在数据库字段比较多的情况下,还是能减少很多工作量的。

    具体更多配置可查看官方文档 参考【8】。




    本文为学习笔记,参考如下!


    【1】:MyBatis-Plus简介
    【2】:Spring Boot 2 (十一):如何优雅的使用 MyBatis 之 MyBatis-Plus
    【3】:最全的Spring-Boot集成Mybatis-Plus教程
    【4】:整合:SpringBoot+Mybatis-plus
    【5】:一起来学SpringBoot(十五)MybatisPlus的整合
    【6】:整合:SpringBoot+Mybatis-plus
    【7】:MyBatis-Plus – 批量插入、更新、删除、查询
    【8】:MyBatis-Plus 代码生成器配置

  • 相关阅读:
    五分钟上手Markdown
    css中居中方法小结
    事务和同步锁
    插入排序
    插入排序
    交换排序
    eclipse 常用快捷键
    交换排序
    二叉搜索树(BST)
    二叉树遍历以及根据前序遍历序列反向生成二叉树
  • 原文地址:https://www.cnblogs.com/three-fighter/p/13986995.html
Copyright © 2020-2023  润新知