SpringBoot入门教程05——整合mybatis-plus(一)

SpringBoot入门教程05——整合mybatis-plus(一)

环境准备

mysql数据库

博主的环境是win10+WSL+docker+mysql8.0+,感兴趣同学的可以参考如下教程,玩一下

  • win10安装linux子系统教程 传送门
  • wsl子系统安装docker,docker安装mysql数据库 传送门
  • wsl子系统开机自启,docker开机自启,docker容器mysql开机自启教程 传送门

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 操作智能分析阻断,也可自定义拦截规则,预防误操作

整合mybatis-plus

修改pom文件

pom.xml添加如下内容

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

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>

修改application.yml文件

username和password改成自己的,url的端口和数据库名也需要改一下,其他参数建议保留,都是有意义的

spring:
  profiles.active: dev

---
spring:
  profiles: dev
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:33006/sample?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8&useSSL=false&useInformationSchema=true
    username: root
    password: 123

新建user表并初始化数据

DROP TABLE IF EXISTS user;

CREATE TABLE user
(
	id BIGINT(20) NOT NULL COMMENT '主键ID',
	name VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',
	age INT(11) NULL DEFAULT NULL COMMENT '年龄',
	email VARCHAR(50) NULL DEFAULT NULL COMMENT '邮箱',
	PRIMARY KEY (id)
);

DELETE FROM user;

INSERT INTO user (id, name, age, email) VALUES
(1, 'Jone', 18, '[email protected]'),
(2, 'Jack', 20, '[email protected]'),
(3, 'Tom', 28, '[email protected]'),
(4, 'Sandy', 21, '[email protected]'),
(5, 'Billie', 24, '[email protected]');

编码

在com.henry包下新建entity包,新建User实体类(此处使用了lombok简化代码)

@Data
public class User {
    
    
    private Long id;
    private String name;
    private Integer age;
    private String email;
}

在com.henry包下新建mapper包,新建UserMapper接口

public interface UserMapper extends BaseMapper<User> {
    
    

}

在com.henry.controller包下新建UserController类

@RestController
@RequestMapping("/user")
public class UserController {
    
    

    @Autowired
    private UserMapper userMapper;

    @RequestMapping("/list")
    public Object list(){
    
    
        List<User> userList = userMapper.selectList(null);
        return userList;
    }

}

在springboot启动类SpringbootDemoApplication类上加注解扫描mapper包

@MapperScan(basePackages = {
    
    "com.henry.mapper"})
@SpringBootApplication
public class SpringbootDemoApplication {
    
    

   public static void main(String[] args) {
    
    
      SpringApplication.run(SpringbootDemoApplication.class, args);
   }
}

重启应用,打开浏览器打开浏览器输入http://127.0.0.1:8080/user/list,浏览器显示:

[{"id":1,"name":"Jone","age":18,"email":"[email protected]"},{"id":2,"name":"Jack","age":20,"email":"[email protected]"},{"id":3,"name":"Tom","age":28,"email":"[email protected]"},{"id":4,"name":"Sandy","age":21,"email":"[email protected]"},{"id":5,"name":"Billie","age":24,"email":"[email protected]"}]

至此springboot整合mybatis-plus的demo就完成了,是不是很简单。

但是编写entity实体类,Mapper接口仍然比较麻烦,幸运的是mybatis-plus也考虑到这点,并提供了完美的解决方案。

mybatis-plus代码生成器

修改pom文件

pom.xml添加如下内容

博主习惯把代码生成器java类放在test目录下,所以scope指定的是test

<dependency>
   <groupId>com.baomidou</groupId>
   <artifactId>mybatis-plus-generator</artifactId>
   <version>3.3.2</version>
   <scope>test</scope>
</dependency>

<dependency>
   <groupId>org.freemarker</groupId>
   <artifactId>freemarker</artifactId>
   <version>2.3.30</version>
   <scope>test</scope>
</dependency>

编码

在src/test/java下com.henry包下新建generator包,然后新建CodeGenerator类

package com.henry.generator;

import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;

import java.util.ArrayList;
import java.util.List;

// 演示例子,执行 main 方法自动生成代码到项目目录中
public class CodeGenerator {
    
    

    public static void main(String[] args) {
    
    
        // 代码生成器
        AutoGenerator generator = new AutoGenerator();

        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir");//项目路径
        gc.setOutputDir(projectPath + "/src/main/java");//生成代码输出路径
        gc.setAuthor("Henry");
        gc.setOpen(false); //是否打开生成代码
        gc.setFileOverride(true);//是否覆盖原有代码,真实项目中一般设为false
        // gc.setSwagger2(true); //实体属性 Swagger2 注解
        gc.setBaseColumnList(false);//xml文件是否生成baseColumnList
        gc.setBaseResultMap(false);//xml文件是否生成baseResultMap
        generator.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://localhost:33006/sample?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8&useSSL=false&useInformationSchema=true");
        // dsc.setSchemaName("public");
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("123");
        generator.setDataSource(dsc);

        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setModuleName(null);//设置模块名,本例是null
//        pc.setModuleName("xxx");
        pc.setParent("com.henry");//生成java代码的包路径
        generator.setPackageInfo(pc);

        // 自定义配置  本例可忽略
        InjectionConfig cfg = new InjectionConfig() {
    
    
            @Override
            public void initMap() {
    
    
                // to do nothing
            }
        };

        // 模板引擎是 freemarker
        String templatePath = "/templates/mapper.xml.ftl";

        // 自定义输出配置
        List<FileOutConfig> focList = new ArrayList<>();
        // 自定义配置会被优先输出  指定xml文件生成路径,本例生成到mapper包下
        focList.add(new FileOutConfig(templatePath) {
    
    
            @Override
            public String outputFile(TableInfo tableInfo) {
    
    
                String rootPath = projectPath + "/src/main/java";
                String pkgPath = pc.getParent().replace(".", "/");
                String path = rootPath + "/" + pkgPath+"/mapper/";

                //看个人习惯,也可以生成到resources/mapper下
//                return projectPath + "/src/main/resources/mapper/" + pc.getModuleName() + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
                // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
                return path + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });

        cfg.setFileOutConfigList(focList);
        generator.setCfg(cfg);

        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();

        // 配置自定义输出模板
        //指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
        // templateConfig.setEntity("templates/entity2.java");

        //disable方法  选择不输出SERVICE接口及实现类,xml配置不输出到xml文件夹
        templateConfig.disable(TemplateType.XML,TemplateType.SERVICE);
        generator.setTemplate(templateConfig);

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
//        strategy.setSuperEntityClass("你自己的父类实体,没有就不用设置!");
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);
        // 公共父类
//        strategy.setSuperControllerClass("你自己的父类控制器,没有就不用设置!");
        // 写于父类中的公共字段
//        strategy.setSuperEntityColumns("id");
        strategy.setInclude("user".split(","));//设置要生成代码的表名,支持正则表达式,"\\w*"代表生成所有表
        strategy.setControllerMappingHyphenStyle(true);//_转驼峰
        strategy.setTablePrefix("core_");//设置表前缀
        strategy.setEntityBooleanColumnRemoveIsPrefix(true);//boolean字段名去掉is
        generator.setStrategy(strategy);
        generator.setTemplateEngine(new FreemarkerTemplateEngine());
        generator.execute();
    }

}

代码生成工具可以生成entity实体类,mapper接口、mapper.xml文件,还可以生成controller和service接口及实现类代码,而且支持按照自定义模板生成代码,使用起来非常简单,功能也很强大。

不过作为用惯了mybatis的程序员,还是觉得操作mapper接口更习惯一些,下面看下myabtis-plus对mapper的crud操作进行了怎样的封装和增强。

Mapper CRUD接口

我们先看一下代码生成工具给我们生成的UserMapper接口

public interface UserMapper extends BaseMapper<User> {
    
    

}

UserMapper继承BaseMapper接口,除此之外,没有其他信息

那我们继续看BaseMapper接口,可以发现所有的方法都定义在BaseMapper中(Mapper是一个空接口)

public interface BaseMapper<T> extends Mapper<T> {
    
    

    /**
     * 插入一条记录
     *
     * @param entity 实体对象
     */
    int insert(T entity);

    /**
     * 根据 ID 删除
     *
     * @param id 主键ID
     */
    int deleteById(Serializable id);

    /**
     * 根据 columnMap 条件,删除记录
     *
     * @param columnMap 表字段 map 对象
     */
    int deleteByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);

    /**
     * 根据 entity 条件,删除记录
     *
     * @param wrapper 实体对象封装操作类(可以为 null)
     */
    int delete(@Param(Constants.WRAPPER) Wrapper<T> wrapper);

    /**
     * 删除(根据ID 批量删除)
     *
     * @param idList 主键ID列表(不能为 null 以及 empty)
     */
    int deleteBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);

    /**
     * 根据 ID 修改
     *
     * @param entity 实体对象
     */
    int updateById(@Param(Constants.ENTITY) T entity);

    /**
     * 根据 whereEntity 条件,更新记录
     *
     * @param entity        实体对象 (set 条件值,可以为 null)
     * @param updateWrapper 实体对象封装操作类(可以为 null,里面的 entity 用于生成 where 语句)
     */
    int update(@Param(Constants.ENTITY) T entity, @Param(Constants.WRAPPER) Wrapper<T> updateWrapper);

    /**
     * 根据 ID 查询
     *
     * @param id 主键ID
     */
    T selectById(Serializable id);

    /**
     * 查询(根据ID 批量查询)
     *
     * @param idList 主键ID列表(不能为 null 以及 empty)
     */
    List<T> selectBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);

    /**
     * 查询(根据 columnMap 条件)
     *
     * @param columnMap 表字段 map 对象
     */
    List<T> selectByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);

    /**
     * 根据 entity 条件,查询一条记录
     *
     * @param queryWrapper 实体对象封装操作类(可以为 null)
     */
    T selectOne(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);

    /**
     * 根据 Wrapper 条件,查询总记录数
     *
     * @param queryWrapper 实体对象封装操作类(可以为 null)
     */
    Integer selectCount(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);

    /**
     * 根据 entity 条件,查询全部记录
     *
     * @param queryWrapper 实体对象封装操作类(可以为 null)
     */
    List<T> selectList(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);

    /**
     * 根据 Wrapper 条件,查询全部记录
     *
     * @param queryWrapper 实体对象封装操作类(可以为 null)
     */
    List<Map<String, Object>> selectMaps(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);

    /**
     * 根据 Wrapper 条件,查询全部记录
     * <p>注意: 只返回第一个字段的值</p>
     *
     * @param queryWrapper 实体对象封装操作类(可以为 null)
     */
    List<Object> selectObjs(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);

    /**
     * 根据 entity 条件,查询全部记录(并翻页)
     *
     * @param page         分页查询条件(可以为 RowBounds.DEFAULT)
     * @param queryWrapper 实体对象封装操作类(可以为 null)
     */
    <E extends IPage<T>> E selectPage(E page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper);

    /**
     * 根据 Wrapper 条件,查询全部记录(并翻页)
     *
     * @param page         分页查询条件
     * @param queryWrapper 实体对象封装操作类
     */
    <E extends IPage<Map<String, Object>>> E selectMapsPage(E page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
}

方法的注释写的很清晰,增删改查CRUD一眼便知,唯一的疑问点是Wrapper是什么以及怎么用?传送门

举个例子,假如现在要查询user表id>=1 and id<=4的数据,我们使用Wrapper来完成该需求,改造一下UserController的list()方法,代码如下:

@RequestMapping("/list")
    public Object list(){
    
    
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.ge("id",1);
        wrapper.le("id",4);
        List<User> userList = userMapper.selectList(wrapper);
        return userList;
    }

重启应用,打开浏览器打开浏览器输入http://127.0.0.1:8080/user/list,自己验证下即可

猜你喜欢

转载自blog.csdn.net/l229568441/article/details/107031230
今日推荐