Spring-boot-mybatisPlus

Spring boot 整合MybatisPlus

上一节 springboot JPA

springboot JPA

源码

源码

MybatisPlus

简介

​ mybatisPlus 是mybatis的一个增强,在mybatis的基础上只做增强不做改变,简化使用mybatis后的代码开发,

使mybaits 更加标准的ORM; 提高开发效率。

mybatisPlus 官网

springboot 整合MybatisPlus

  1. 添加依赖

    springboot 项目中我们引入mybatisPlus 的starter

 <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
<!--mybatisPlus starter-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.2</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
  1. 配置文件中配置相关信息

    spring:
      application:
        name: mybatisplus-demo
    ## 数据源配置
      datasource:
        url: jdbc:mysql://localhost:3306/mytest?useSSL=false&charsetEncoding=utf8
        username: root
        password: 123456
        driver-class-name: com.mysql.jdbc.Driver
    ## mybatis puls 相关配置
    mybatis-plus:
      configuration:
        map-underscore-to-camel-case: true # 默认true 下划线和驼峰命名转换
        ## sql 打印
        log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
        ## 配置 mapper 文件的相关位置
      mapper-locations: classpath:mapper/**/*.xml
      ## 别名
      type-aliases-package: com.xiaodu.springboot.mybatis.plus.entity 
    
sql 打印
	配置mybatisPlus 的 log-impl
mybatis-plus:
  configuration:
    ## sql 打印
    log-impl: org.apache.ibatis.logging.stdout.StdOutImp
  1. 创建相关的entity, mapper

    entity

    @Data
    public class UserEntity {
    
        private String uId;
    
        private String uName;
    
    }
    

    mapper

    @Mapper
    public interface UserMapper {
        void insertUser(UserEntity userEntity);
    }
    

    mapper.xml

    <!DOCTYPE mapper
            PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    
    <mapper namespace="com.xiaodu.springboot.mybatis.plus.mapper.UserMapper">
    
        <insert id="insertUser" parameterType="userEntity">
           insert into t_user  values(#{uId}, #{uName})
        </insert>
    
    </mapper>
    

    以上和我们在mybatis 中的使用一模一样,这也提现了mybaitsPlus 的特性,不做更改,低侵入。

    测试运行

    @SpringBootApplication
    public class MybatisPlusApplication implements ApplicationRunner {
    
        @Autowired
        private UserMapper userMapper;
    
    
        public static void main(String[] args) {
    
            SpringApplication.run(MybatisPlusApplication.class, args);
        }
    
        @Override
        public void run(ApplicationArguments args) throws Exception {
            UserEntity userEntity = new UserEntity();
            userEntity.setUId("11111");
            userEntity.setUName("222222");
            userMapper.insertUser(userEntity);
        }
    }
    

mybatisPlus 通用mapper

​ mybaits Plus 内置了通用mapper, 我们只需要继承baseMapper 即可实现简单的CRUD

  1. mapper 继承 BaseMapper

    @Mapper
    public interface UserMapper extends BaseMapper<UserEntity> {
    
        void insertUser(UserEntity userEntity);
    }.
    
  2. 实体类添加相关注解映射信息

    @Data
    @TableName(value = "t_user")
    public class UserEntity {
    
        @TableId(value = "u_id", type = IdType.AUTO)
        private String uId;
    
        @TableField(value = "u_name")
        private String uName;
    }
    

    这样我们就可以使用BaseMapper中的所有方法,而不需要自己写mapper 和sql

    baseMapper 中的crud方法

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-kUgJhetN-1625032636014)(C:\Users\huayu\AppData\Roaming\Typora\typora-user-images\1621386879181.png)]

    MybatisPlus 提供的实体映射相关注解

    官方文档注解

    @TableName

    使用在entity类上,表名映射

    属性类型是否必须默认值描述
    valueStringN“”表名
    schemaStringN”“数据库模式名
    keepGlobalPrefixbooleanNfalse是否保持使用全局的 tablePrefix 的值
    resultMapStringN“”结果集映射,对应xml中或者注解中resultMap的ID
    excludePropertyString[]N{}需要排除的属性名
    autoResultMapbooleanNfalse是否自动构建 resultMap 并使用(如果设置 resultMap 则不会进行 resultMap 的自动构建并注入)

    @TableId

    标注在属性上,主键注解; 如果字段为id; 则不加该注解,mybatisPlus也以识别为字段为主键

    属性类型是否必须默认值描述
    valueStringN“”主键字段名
    typeEnumNIdType.NONE主键类型

    IdType简述

    描述
    AUTO支持数据主键自增
    NONE不设置,默认等于INPUT类型 用户自己设置ID
    INPUT用户输入ID
    ASSIGN_ID分布式id(雪花算法生成)
    ASSIGN_UUID使用uuid生成id

    @TableField

    标注在字段上,表字段标识

    属性类型是否必须默认值描述
    valueStringN“”数据库字段值,默认开启下划线转驼峰
    existbooleanNtrue是否为数据库表字段
    conditionStringNSqlCondition.EQUAL字段 where 实体查询比较条件
    updateStringN“”字段 update set 部分注入, 该注解优于 el 注解使用 . 例1:@TableField(… , update="%s+1") 其中 %s 会填充为字段 输出 SQL 为:update 表 set 字段=字段+1 where … 例2:@TableField(… , update=“now()”) 使用数据库时间*输出 SQL 为:update 表 set 字段=now() where …
    insertStrategyFieldStrategyNFieldStrategy.DEFAULT当为insert操作时,验证字段拼接sql时的验证策略;例如判断是否为null 的策略FieldStrategy.NOT_NULL; 其他具体参照官网或者源码
    updateStrategyFieldStrategyNFieldStrategy.DEFAULT当为update操作时,验证字段拼接sql时的验证策略;同insertStrategy
    whereStrategyFieldStrategyNFieldStrategy.DEFAULTwhere 条件验证策略
    fillFieldFillNFieldFill.DEFAULT字段填填充策略
    selectbooleanNtrue是否是select 查询语句中查询字段
    jdbcTypeJdbcTypeNJdbcType.UNDEFINEDJDBC类型
    typeHandlerTypeHandlerNUnknownTypeHandler.class类型处理器
MybatisPlus 通用Service

​ MybatisPlus 内置了Iservice 和他的实现类 ServiceImpl, 提供了基本的crud 以及按照条件 和分页查询,count等常用方法。

使用

  1. 继承Iservice

    public interface UserService extends IService<UserEntity> {
    }
    
  2. 实现类继承ServiceImpl, 同时实现我们自己的service,这样我们也可以写自己的逻辑方法

    @Service
    @Slf4j
    public class UserServiceImpl extends ServiceImpl<UserMapper, UserEntity> implements UserService {
    
    }
    
    

    测试

        public void testBaseService() {
            System.out.println(userService.getById("123"));
            System.out.println(userService.count());
        }
    
    
MybatisPlus 分页

springboot 项目中集成

  1. 添加分页插件
    // mybatisPlus 分页
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
       MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
        PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor(DbType.MYSQL);
        paginationInnerInterceptor.setMaxLimit(1000L);
        paginationInnerInterceptor.setOverflow(false);
        mybatisPlusInterceptor.addInnerInterceptor(paginationInnerInterceptor);
       return mybatisPlusInterceptor;
    }
  1. 方法调用传入参数page

    // 构建page	
    Page<UserEntity> page = new Page<>(1,3);
    // 分页查询
    Page<UserEntity> page1 = userService.page(page);
    // 获取数据
    System.out.println(page1.getRecords());
    
MybatisPlus 条件查询

​ MybatisPlus 封装了Wrapper 进行条件的构造; 通常使用他的字类 QueryWrapper 和 UpdateWrapper,以及他们的lambda形式: LambdaQueryWrapper 和 LambdaUpdateWrapper

使用示例

QueryWrapper

​ 查询条件封装

        // queryWrapper
        QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<>();
        // 使用like,column 为数据库字段
        queryWrapper.like("u_name", "110");
        //SELECT u_id,u_name FROM t_user WHERE (u_name LIKE ?)
        List list = userService.list(queryWrapper);

QueryWrapper 继承字AbstractWrapper,AbstractWrapper提供了大量的sql条件拼接,例如:

  • allEq

  • eq

  • ne

  • get

  • ge

  • lt

  • le

  • between

  • notBetween

  • like

  • notLike

  • likeLeft

  • isNull

  • in

  • notIn

  • or

  • and

  • 具体使用很简单,可以参考官方文档Mybatis-Plus 条件构造器

queryWrapper也支持传入一个Entity,entity中使用注解 @TableFiled 通过codition进行where查询比较条件;

  // 使用  @TableField 设置  condition = SqlCondition.LIKE;进行like 操作
        UserEntity u = new UserEntity();
        u.setUName("aaa");
        QueryWrapper<UserEntity> queryWrapper1 = new QueryWrapper<>(u);
        // SELECT u_id,u_name FROM t_user WHERE u_name LIKE CONCAT('%',?,'%')
        System.out.println(userService.list(queryWrapper1));
UpdateWrapper

​ update语句条件封装

 // updateWrapper
        UpdateWrapper<UserEntity> updateWrapper = new UpdateWrapper<>();
        updateWrapper
                .set("u_id", "123")
                .set("u_name", "aaa")
                .eq("u_id", "123"); // 条件
        // UPDATE t_user SET u_id=?,u_name=? WHERE (u_id = ?)
        System.out.println(userService.update(updateWrapper));

​ 接收两个参数的条件封装

        UserEntity userEntity = new UserEntity();
        UpdateWrapper<UserEntity> updateWrapper2 = new UpdateWrapper<>();
        updateWrapper2.eq("u_id","123");
        userEntity.setUName("aaa");
        // 接收2个参数,第一个参数为 set的值, 第二个参数updateWrapper 为条件
        // UPDATE t_user SET u_name=? WHERE (u_id = ?)
        System.out.println(userService.update(userEntity, updateWrapper2));
LambdaQueryWrapper

lambdaQueryWrapper 和queryWrapper使用上基本一致的,只不过运用了lambda的语法特性进行条件的构造。

      // LambdaQueryWrapper
        LambdaQueryWrapper<UserEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.select(UserEntity::getUId)
                .eq(UserEntity::getUName, "aaa");
        System.out.println(userService.list(lambdaQueryWrapper));
LambdaUpdateWrapper
    // LambdaUpdateWrapper
       LambdaUpdateWrapper<UserEntity> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
       lambdaUpdateWrapper.set(UserEntity::getUName,"bbb")
                .eq(UserEntity::getUId,"123");
       System.out.println(userService.update(lambdaUpdateWrapper));

MybatisPlus AR

mybatisPlus 扩展的ActiveRecord 模式,即领域模型;简单说就是 数据库和实体映射,操作实体就是在操作数据库,而不用在通过dao或者mapper。

使用示例

我们直接操作实体就能又mapper的功能

    private void testAR() {
        UserEntity userEntity = new UserEntity();
        System.out.println(userEntity.selectAll());
        userEntity.selectOne(new LambdaUpdateWrapper<UserEntity>().eq(UserEntity::getUId,"123"));
        userEntity.selectList(new LambdaQueryWrapper<UserEntity>().like(UserEntity::getUName,"aaa"));
    }

主键生成策略

前面我已经知道了在@TableId 上指定 type 来设置主键的生成策略; 并且 mybatisplus 默认提供的IdType 支持

  1. AUTO(数据库自增)

  2. NONE(不设置,等于全局设置)

  3. INPUT(用户输入)

  4. ASSIGN_ID(分布式id,雪花算法)

  5. ASSIGN_UUID(UUID)

    @TableId(value = "u_id", type = IdType.ASSIGN_ID)
        private String uId;
    ...
        
        
        private void testId() {
            UserEntity userEntity  = new UserEntity();
            userEntity.setUName("aaa");
            //INSERT INTO t_user ( u_id, u_name ) VALUES ( ?, ? )
            //Parameters: 1396074749305671681(String), aaa(String); 自动生成了id
            userEntity.insert();
        }
    

    上面示例我们使用分布式id生成策略,mybatisplus 在insert操作的时候会自动生成id。

逻辑删除

​ 逻辑删除不同于物理删除,就是数据还在,增加一个是否删除的标识;逻辑删除执行的是update语句,查询的时候带上这个标识的判断;

例如 字段 is_del, 他的值为 1 和0 ; 1为真 0为假; 查询的时候带上条件 is_del = 1; 删除的时候为update table set is_del = 1; 添加的时候 默认0即可。

mybatisplus 帮我们省去了这些麻烦的操作,我们只需要添加一个注解@TableLogic 即可

mybatisplus逻辑删除的默认值, 一般情况下使用默认值即可。

// mybatisplus 源码中逻辑删除的定义 
/**
         * 逻辑删除全局值(默认 1、表示已删除)
         */
        private String logicDeleteValue = "1";
        /**
         * 逻辑未删除全局值(默认 0、表示未删除)
         */
        private String logicNotDeleteValue = "0";

如何使用

​ 记得在库表中添加该字段

​ alter table t_user add column is_del tinyint not null;

​ 实体类添加标识字段, 数据库中也同样添加

 @TableField(value ="is_del")
    @TableLogic
    private String del;
    // 测试逻辑删除
    private void testTableLogic() {
        UserEntity u = new UserEntity();
        String id = "logic";
        u.setUId(id);
        u.setUName("testLogic");
        // 逻辑删除对插入是不做限制的, 所以需要我们手动设置
        u.setDel(0);
        // INSERT INTO t_user ( u_id, u_name, is_del ) VALUES ( ?, ?, ? )
        boolean insert = u.insert();
        
        System.out.println("---------删除--------");
        // UPDATE t_user SET is_del=1 WHERE u_id=? AND is_del=0
        // 删除执行的update 语句, set is_del = 1;
        u.deleteById();
        
        System.out.println("**********更新*********");
        //UPDATE t_user SET u_name=? WHERE u_id=? AND is_del=0
        // 也会带上条件  is_del =0 (没被删除的才会更新)
        u.updateById();

        System.out.println("===查询=====");
        // SELECT u_id,u_name,is_del AS del FROM t_user WHERE u_id=? AND is_del=0
        // 查询语句中自动添加条件 is_del = 0
        UserEntity userEntity = u.selectById();

    }

通过测试可知:

(0 为 否, 1 为是)

  1. 新增:不做操作
  2. 删除:where条件会带上is_del = 0, 并设置 set is_del=1
  3. 更新: where条件会带上is_del=0
  4. 查询: where条件会带上is_del =0

改变逻辑删除字段默认值

  1. 通过 注解@TableLogic

     // 配置 1 是 2否
        @TableLogic(value = "2", delval = "1")
        private Integer del;
    
    1. 全局配置
    mybatis-plus:
      global-config:
        db-config:
          logic-delete-field: flag  # 全局逻辑删除的实体字段名(since 3.3.0,配置后可以忽略不配置步骤2)
          logic-delete-value: 1 # 逻辑已删除值(默认为 1)
          logic-not-delete-value: 0 # 逻辑未删除值(默认为 0)
    

自动填充功能

在 阿里巴巴开发规范中说明:

【强制】表必备三字段: id , gmt _ create , gmt _ modified

所以我们按照规范说明添加 创建时间 gmt_create, 更新时间 gmt_modified

alter table t_user add column gmt_create datetime not null;

alter table t_user add column gmt_modified datetime not null;

这个字段是必须的,我们在mybaits 篇章中 通过 使用mybatis的拦截器 进行了 创建时间和更新时间的设置;

现在这个mybatisplus 自动帮助我们做了。

如何使用

使用 @TableFiled 的填充属性fill

    @TableField(value ="is_del", fill = FieldFill.INSERT)
    // 配置 1 是 2否
    @TableLogic(value = "2", delval = "1")
    private Integer del;

    @TableField(fill = FieldFill.INSERT)
    private LocalDateTime gmtCreate;

    @TableField (fill = FieldFill.INSERT_UPDATE)
    private LocalDateTime gmtModified;

添加 MetaObjectHandler

    @Bean
    public MetaObjectHandler dateTimeMetaObjectHandler() {
        return new MetaObjectHandler(){

            @Override
            public void insertFill(MetaObject metaObject) {
                // insert
                this.strictInsertFill(metaObject, "gmtCreate",LocalDateTime::now, LocalDateTime.class);
                // update
                this.strictUpdateFill(metaObject, "gmtModified", LocalDateTime::now, LocalDateTime.class);
                // del 逻辑删除字段默认值
                this.strictInsertFill(metaObject, "del",() -> 2, Integer.class);
            }

            @Override
            public void updateFill(MetaObject metaObject) {
                this.strictUpdateFill(metaObject, "gmtModified", LocalDateTime::now, LocalDateTime.class);
            }
        };
    }

使用示例

    // 测试自动填充
    private void testFill() {
        UserEntity u = new UserEntity();
        u.setUName("fill");
        // INSERT INTO t_user ( u_id, u_name, is_del, gmt_create, gmt_modified ) VALUES ( ?, ?, ?, ?, ? )
        u.insert();
        // UPDATE t_user SET u_name=?, gmt_create=?, gmt_modified=? WHERE u_id=? AND is_del=2
        u.updateById();
    }

乐观锁

通过 数据库字段version 进行 CAS 乐观锁操作。

  1. 添加 version 字段

    alter table t_user add column version varchar(12) not null;
    
  2. 修改entity

        @Version
        private Integer version;
    
  3. 添加插件

    (之前我们添加过分页插件,这次添加乐观锁插件 OptimisticLockerInnerInterceptor)

        @Bean
        public MybatisPlusInterceptor mybatisPlusInterceptor() {
           MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
            PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor(DbType.MYSQL);
            paginationInnerInterceptor.setMaxLimit(1000L);
            paginationInnerInterceptor.setOverflow(false);
            // 分页
            mybatisPlusInterceptor.addInnerInterceptor(paginationInnerInterceptor);
            // 乐观锁
            mybatisPlusInterceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
           return mybatisPlusInterceptor;
        }
    

mybatisplus 中的说明

当要更新一条记录的时候,希望这条记录没有被别人更新
乐观锁实现方式:

  • 取出记录时,获取当前version
  • 更新时,带上这个version
  • 执行更新时, set version = newVersion where version = oldVersion
  • 如果version不对,就更新失败

只在更新操作中生效,并且需要带上这个字段。

取出信息,获取当前version, 执行更新操作 带上当前的version, 如果此时数据库version 变了则更新失败

    UserEntity u = new UserEntity();
        u.setUId("1396683484596064257");
        // 获取信息
        UserEntity userEntity = u.selectById();

        // 更新name, 并且带上version字段。
        u.setVersion(userEntity.getVersion());
        u.setUName("Bbb" + UUID.randomUUID());
        // UPDATE t_user SET u_name='Bbb23266788-cb7e-4454-b68d-ef6bc230b09c',
        // gmt_modified='2021-05-24T12:34:51.992', version=5
        // WHERE u_id='1396683484596064257' AND version=4 AND is_del=2
        u.updateById();

sql分析

使用 p6spy 进行sql分析

  1. 添加依赖

         <dependency>
                <groupId>p6spy</groupId>
                <artifactId>p6spy</artifactId>
                <version>3.8.1</version>
            </dependency>
    
  2. 修改配置文件

    # URL 修改,jdbc后面添加p6spy 
    url: jdbc:p6spy:mysql://localhost:3306/mytest?useSSL=false&charsetEncoding=utf8
    # 驱动修改
     driver-class-name: com.p6spy.engine.spy.P6SpyDriver
    
  3. 添加spy.properties进行 p6spy的配置

    在 resources 下面添加spy.properties文件

    #3.2.1以上使用
    modulelist=com.baomidou.mybatisplus.extension.p6spy.MybatisPlusLogFactory,com.p6spy.engine.outage.P6OutageFactory
    #3.2.1以下使用或者不配置
    #modulelist=com.p6spy.engine.logging.P6LogFactory,com.p6spy.engine.outage.P6OutageFactory
    # 自定义日志打印
    logMessageFormat=com.baomidou.mybatisplus.extension.p6spy.P6SpyLogger
    #日志输出到控制台
    appender=com.baomidou.mybatisplus.extension.p6spy.StdoutLogger
    # 使用日志系统记录 sql
    #appender=com.p6spy.engine.spy.appender.Slf4JLogger
    # 设置 p6spy driver 代理
    deregisterdrivers=true
    # 取消JDBC URL前缀
    useprefix=true
    # 配置记录 Log 例外,可去掉的结果集有error,info,batch,debug,statement,commit,rollback,result,resultset.
    excludecategories=info,debug,result,commit,resultset
    # 日期格式
    dateformat=yyyy-MM-dd HH:mm:ss
    # 实际驱动可多个
    driverlist= com.mysql.jdbc.Driver
    # 是否开启慢SQL记录
    outagedetection=true
    # 慢SQL记录标准 2 秒
    outagedetectioninterval=2
    

运行项目 可见控制台打印

 Consume Time:39 ms 2021-05-22 21:10:33
 Execute SQL:INSERT INTO t_user ( u_id, u_name, is_del, gmt_create, gmt_modified ) VALUES ( '1396091107942666241', 'fill', 2, '2021-05-22T21:10:32.918', '2021-05-22T21:10:32.918' )

数据库用户名密码加密

使用mybatisPlus自带的加密工具加密

    public static void main(String[] args) {
        String s = AES.generateRandomKey();
        String username = "root";
        String password = "123456";
        String url = "jdbc:p6spy:mysql://localhost:3306/mytest?useSSL=false&charsetEncoding=utf8";
        System.out.println("key =" + s);
        System.out.println(AES.encrypt(username, s));
        System.out.println(AES.encrypt(password, s));
        System.out.println(AES.encrypt(url, s));
    }

生成的key 和加密后的数据保存好。

配置文件中修改数据库用户名密码

  url: mpw:jYoCfq1RcJ0xs1/MSYspjNoLXPrsSDBCFsB61G40OUkRpTNoNZMZ72bHijGzDRMBBU7EcKwS9dWIbeCE4m4gRKNQ2yO7TLYziBRJzdUJ+f8=
username: mpw:O0aFzrgeCOMRKwdRToRJmw==
password: mpw:5l9rx+CASGjdBeaetck8MA==

如何使用

  1. 第一种使用方式:如果是服务器可以设置环境变量

  2. 第二种使用方式:使用jar 启动, 添加 启动参数

    --mpw.key=1fc81d46e2680110
    
  3. 第三种使用方式:idea 中配置 program arguments

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-QPYAwgWi-1625032636018)(C:\Users\huayu\AppData\Roaming\Typora\typora-user-images\1621690241987.png)]

MybatisPlus Generator

​ mybatisPlus Generator 代码生成器可以快速生成entity,mapper,mapperXML,service, controller 等各个模块的代码,提高开发效率。

添加依赖

     <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>

编写Generator类

  • 全局配置 globalconfig

            GlobalConfig globalConfig = new GlobalConfig();
            // 配置生成的文件输出目录
            globalConfig.setOutputDir(System.getProperty("user.dir") + "\\xiaodu-springboot-mybatis-plus\\src\\main\\java");
            // author
            globalConfig.setAuthor("dtj");
    
            globalConfig.setOpen(false);
            // 实体名称
            globalConfig.setEntityName("%sTable");
            // controller名称
            globalConfig.setControllerName("%sController");
            // service名称
            globalConfig.setServiceName("I%sService");
            // serviceImpl名称
            globalConfig.setServiceImplName("%sServiceImpl");
            // 是否开启 ar
            globalConfig.setActiveRecord(true);
            // 是否生成xml中的baseResultMap
            globalConfig.setBaseResultMap(true);
            // id生成策略
            globalConfig.setIdType(IdType.ASSIGN_ID);
            // 是否开启swagger2
            globalConfig.setSwagger2(true);
    
  • 数据源配置

      // 数据源配置
            DataSourceConfig dataSourceConfig = new DataSourceConfig();
            dataSourceConfig.setUrl("jdbc:mysql://localhost:3306/mytest?useSSL=false&charsetEncoding=utf8");
            dataSourceConfig.setUsername("root");
            dataSourceConfig.setPassword("123456");
            dataSourceConfig.setDriverName("com.mysql.jdbc.Driver");
            dataSourceConfig.setDbType(DbType.MYSQL);
    
  • 包配置

       // 生成文件的包配置
            PackageConfig packageConfig = new PackageConfig();
            packageConfig.setParent("com.mybatisplus.domo");
    
    
  • 生成策略配置

      // 策略配置
            StrategyConfig strategyConfig = new StrategyConfig();
            // 下划线转驼峰
            strategyConfig.setNaming(NamingStrategy.underline_to_camel);
            // 生成哪些表名的映射文件
            strategyConfig.setInclude(new String[]{"sys_user_role", "sys_user_post"});
    
    
  • 使用AutoGenerator 生成

      AutoGenerator autoGenerator = new AutoGenerator();
            autoGenerator.setDataSource(dataSourceConfig);
            autoGenerator.setGlobalConfig(globalConfig);
            autoGenerator.setTemplateEngine(new VelocityTemplateEngine());
            autoGenerator.setPackageInfo(packageConfig);
            autoGenerator.setStrategy(strategyConfig);
            autoGenerator.execute();
    

以上是springboot 整合mybatisPlus,以及一些常用的配置和使用。

a
// 生成文件的包配置
PackageConfig packageConfig = new PackageConfig();
packageConfig.setParent(“com.mybatisplus.domo”);




* 生成策略配置

```java
  // 策略配置
        StrategyConfig strategyConfig = new StrategyConfig();
        // 下划线转驼峰
        strategyConfig.setNaming(NamingStrategy.underline_to_camel);
        // 生成哪些表名的映射文件
        strategyConfig.setInclude(new String[]{"sys_user_role", "sys_user_post"});

  • 使用AutoGenerator 生成

      AutoGenerator autoGenerator = new AutoGenerator();
            autoGenerator.setDataSource(dataSourceConfig);
            autoGenerator.setGlobalConfig(globalConfig);
            autoGenerator.setTemplateEngine(new VelocityTemplateEngine());
            autoGenerator.setPackageInfo(packageConfig);
            autoGenerator.setStrategy(strategyConfig);
            autoGenerator.execute();
    

以上是springboot 整合mybatisPlus,以及一些常用的配置和使用。

下一节

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值