小工具知识网

当前位置: 首页 > 行业知识 > SpringBoot整合Mybatis-plus[超详细版]

行业知识

SpringBoot整合Mybatis-plus[超详细版]

2026-11-10 22:42:26 来源:互联网转载

目录

一简介

1、什么是Mybatis-plus

2、特性

二、SpringBoot与Mybatis-plus整合之入门demo

1、引入pom

2、application.yml配置

3、主启动类

 4、测试

entity层

Mapper层

Service和ServiceImpl层

controller测试

三、Mybatis-plus核心注解

@TableName

@TableId

@TableField

@KeySequence  

 四、Mybatis-Plus之分页插件

1、config配置

2、 分页的使用

2.1、mybaits-plus自带的分页查询

2.2、自定义分页

2.2.1、自定义mapper接口

2.2.2、service实现自定义分页

五、Mybatis-plus逆向工程


一简介

1、什么是Mybatis-plus

Mybatis-Plus(简称MP)是一个Mybatis的增强工具,只是在Mybatis的基础上做了增强却不做改变,MyBatis-Plus支持所有Mybatis原生的特性,所以引入Mybatis-Plus不会对现有的Mybatis构架产生任何影响。MyBatis 增强工具包,简化 CRUD 操作。启动加载 XML 配置时注入单表 SQL 操作 ,为简化开发工作、提高生产率而生。

官网:https://baomidou.com

2、特性

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

    二、SpringBoot与Mybatis-plus整合之入门demo

    依赖>配置>代码

    1、引入pom

                        com.baomidou            mybatis-plus-boot-starter            3.5.1                            mysql            mysql-connector-java                                    com.alibaba            druid-spring-boot-starter            1.1.18        

     

    2、application.yml配置

    mybatis-plus:  configuration:    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl  #日志    map-underscore-to-camel-case: true  #开启驼峰命名spring:  datasource:    type: com.alibaba.druid.pool.DruidDataSource    username: 自己的用户名    password: 自己的密码    driver-class-name: com.mysql.cj.jdbc.Driver    url: jdbc:mysql://localhost/cardmanager

    3、主启动类

    @SpringBootApplication//注意:扫描包路径必须要精确到Mapper包,否则报异常@MapperScan(basePackages = "扫描自己的mapper路径")public class SpringBootThree {    public static void main(String[] args) {        SpringApplication.run(SpringBootThree.class,args);    }}

     4、测试

    entity层

    public class User {    @TableId(type = IdType.AUTO)    private Long id;    private String name;    private String password;    private String username;    public User() {    }    public User(Long id, String name, String password, String username) {        this.id = id;        this.name = name;        this.password = password;        this.username = username;    }    public Long getId() {        return id;    }    public void setId(Long id) {        this.id = id;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public String getPassword() {        return password;    }    public void setPassword(String password) {        this.password = password;    }    public String getUsername() {        return username;    }    public void setUsername(String username) {        this.username = username;    }    @Override    public String toString() {        return "User{" +                ", name='" + name + '\'' +                ", password='" + password + '\'' +                ", username='" + username + '\'' +                '}';    }}

    Mapper层

    BaseMapper是mybatis-plus设计的一个接口,里面包含了单表的CRUD,用起来非常方便.

    表示实体类

    @Repositorypublic interface UserMapper  extends BaseMapper{}

    Service和ServiceImpl层

    IService和ServiceIMpl 是对BaseMapper的进一步封装,一般很少用。但是很方便。

    public interface UserService extends IService{}

     

    //impl层@Servicepublic class UserServiceImpl extends ServiceImpl implements UserService {    @Autowired    UserMapper userMapper;}

    controller测试

    @Controllerpublic class UserController { @Autowired    UserService userService;@RequestMapping("/test")    public String TestUser(@RequestParam("id") Long id){             User user = userService.getById(id);           System.out.print(user)    }}

    好!到上述是一个SpringBoot整合Myabtisplus的入门小案例。接下来才是主要的部分

    三、Mybatis-plus核心注解

    @TableName

    • 描述:表名注解,标识实体类对应的表
    • 使用位置:实体类
      @TableName("user")public class User {    @TableId(type = IdType.AUTO)    private Long id;    private String name;    private String password;    private String username;}
      属性描述
      value表名
      keepGlobalPrefix是否保持使用全局的 tablePrefix 的值(当全局 tablePrefix 生效时)
      resultMapxml 中 resultMap 的 id(用于满足特定类型的实体类对象绑定)

      @TableId

      • 描述:主键注解
      • 使用位置:实体类主键字段
        @TableName("user")public class User {    @TableId(type = IdType.AUTO)    private Long id;    private String name;    private String password;    private String username;}
        属性默认值描述
        value""主键字段名
        typeIdType.NONE制定主键类型

        IdType    

          一般都是数据库自增,或者就是自己设置主键id

        值描述
        AUTO数据库 ID 自增
        NONE无状态,该类型为未设置主键类型(注解里等于跟随全局,全局里约等于 INPUT)
        ASSIGN_ID分配 ID(主键类型为 Number(Long 和 Integer)或 String)(since 3.3.0),使用接口IdentifierGenerator的方法nextId(默认实现类为DefaultIdentifierGenerator雪花算法)
        ASSIGN_UUID分配 UUID,主键类型为 String(since 3.3.0),使用接口IdentifierGenerator的方法nextUUID(默认 default 方法)

        @TableField

        • 描述:字段注解(非主键)
          @TableName("user")public class User {    @TableId(type = IdType.AUTO)    private Long id;    @TableField("t_name")    private String name;    @TableField("t_pwd")    private String password;     @TableField("t_username")    private String username;        //表示是否为数据库字段,在进行mybatis-plus封装的CRUD时,不会携带这个字段进行数据库的查询    @TableField(exist=false)       //自定义类型        private Dept dept;}
          属性默认值描述
          value""数据库字段名
          existtrue是否为数据库表字段
          condition""字段 where 实体查询比较条件,有值设置则按设置的值为准,没有则为默认全局的 %s=#{%s}
          update""字段 update set 部分注入,例如:当在version字段上注解update="%s+1" 表示更新时会 set version=version+1 (该属性优先级高于 el 属性)

          上述表格中,只有前两个最常用,其他的看看就行,一般不用

          @KeySequence  

          • 描述:序列主键策略 oracle
          • 属性:value、dbType
            属性默认值描述
            value""序列名
            dbTypeDbType数据库类型,未配置默认使用注入 IKeyGenerator 实现,多个实现必须指定

            好了,上述就是最常用的注解,如果想看更多前往官网地址:注解 | MyBatis-Plus (baomidou.com)

             四、Mybatis-Plus之分页插件

            1、config配置

            使用mybatis-plus的分页时,必须配置config,否者分页插件不生效

            @Configurationpublic class MyBaitsPlusConfig {        //配置分页插件        @Bean        public MybatisPlusInterceptor mybatisPlusInterceptor() {            MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();            //数据库类型是MySql,因此参数填写DbType.MYSQL            interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));            return interceptor;        }}

            2、 分页的使用

            2.1、mybaits-plus自带的分页查询

            @Servicepublic class UserServiceImpl extends UserImpl implements UserService {    @Autowired    UserMapper userMapper;    @Override    public Page memberList(Integer pageNum, User user) {        /**            在查询之前实例化Page(当前页,每页显示的个数)             page实体类创建完成之后,会将你查询出来的结果封装到里边的records属性中                使用getRecords()方法调用           */        Page page = new Page(pageNum,5);            //mybatis-plus自带的单表分页查询            /**            selectPage(P page, @Param(Constants.WRAPPER) Wrapper queryWrapper)                参数1:一个分页对象                参数2:表示分页查询的条件,如果没有可以为null        */         userMapper.selectPage(page, null);        /**-------带条件的分页查询-----         QueryWrapper queryWrapper =   new QueryWrapper();                queryWrapper.eq("数据库字段名称",对应传过来的实体类字段名称) //精准查询                                //模糊查询                            .like("数据库字段名称",对应传过来的实体类字段名称);          userMapper.selectPage(page, queryWrapper);            */        return page;    }}

            2.2、自定义分页

            自定义分页的时候就涉及到了连表的查询,这个时候我们就要自己自定义分页!

            2.2.1、自定义mapper接口

            @Repositorypublic interface UserMapper extends BaseMapper {    //注意分页参数的分页,一定要在第一个参数    Page userList(IPage page, @Param("user")User user);}//对应的xml文件自己写

            2.2.2、service实现自定义分页

            @Servicepublic class UserServiceImpl extends UserImpl implements UserService {    @Autowired    UserMapper userMapper;    @Override    public Page memberList(Integer pageNum, User user) {        /**            在查询之前实例化Page(当前页,每页显示的个数)             page实体类创建完成之后,会将你查询出来的结果封装到里边的records属性中                使用getRecords()方法调用           */        Page page = new Page(pageNum,5);         memberBrMapper.memberList(page, user);        return page;    }}

            五、Mybatis-plus逆向工程

            #联合mybatisplus使用    com.baomidou    mybatis-plus-generator    3.5.1    org.freemarker    freemarker    2.3.31
            public class FastAutoGeneratorTest {public static void main(String[] args){    FastAutoGenerator.create("jdbc:mysql://localhost:3306/自己的表名", 用户名, 密码)            .globalConfig(builder -> {                builder.author("wdc") // 设置作者//                        .enableSwagger() // 开启 swagger 模式                        .fileOverride() // 覆盖已生成文件                                                .outputDir("D://springbootcards"); // 指定输出目录            })            .packageConfig(builder -> {                builder.parent("com.atdession") // 设置父包名                        .moduleName("springbootcards") // 设置父包模块名                            .entity("entity") //都是设置名称的                            .service("service")                            .serviceImpl("service.impl")                            .controller("controller")                            .mapper("mapper")                            .xml("mapper")                        .pathInfo(Collections.singletonMap(OutputFile.mapperXml, "D://springbootcards")); // 设置mapperXml生成路径            })            .strategyConfig(builder -> {                builder.addInclude("user","dept"); // 设置需要生成的表名                     .serviceBuilder().formatServiceFileName("%sService");//设置去掉Service的前缀I//                        .addTablePrefix("t_", "c_"); // 设置过滤表前缀            })            .templateEngine(new FreemarkerTemplateEngine()) // 使用Freemarker引擎模板,默认的是Velocity引擎模板            .execute();}}

             

上一篇:怎么进小包服务器界面设置?

下一篇:多线程练习题记录