Spring-boot-mybatisPlus

spring boot整合dubbo加入mybatis,mybatisplus(Client) 首先我们先用myeclipse创建一个maven项目(可直接去dubbo官网生成http://start.dubbo.io/)。 码云demo地址:https://gitee.com/itCjb/Springboot-dubbo-mybatisplus 目录结构: 接下来复制一下pom配置(根据自己所需) <project xmlns="http://maven.apache.... 阅读详情

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,以及一些常用的配置和使用。

下一节

MyBatisPlus入门指南与Spring Boot项目集成实战 MyBatisPlus(简称MP)是MyBatis的增强工具,遵循“无侵入、强功能、零SQL”的设计理念,在不改变MyBatis原有特性的前提下,通过封装大量通用操作,显著提升开发效率。其核心目标是减少DAO层冗余代码,实现CRUD操作的自动化。某些场景下主键具有业务含义,如订单号,此时应使用INPUT策略:此时必须由业务逻辑显式赋值,否则报错。尽管IService。 阅读详情

相关推荐

Spring Boot自定义响应与MyBatisPlus集成实践

在Web开发中,返回统一格式的响应体是一种常见的实践,能够增强前后端的交互一致性和系统的可维护性。Spring Boot提供了多种方式来实现自定义响应体,本章将重点介绍如何在Spring Boot框架中实现和优化自定义响应功能。自定义响应体可以提高API的可用性和可维护性,它让客户端开发者能够明确知道接口的响应结构,包括成功与错误时的格式。在微服务架构中,统一的响应体格式对于服务之间的通信尤其重要。自定义响应体通常涉及到创建一个通用的响应类,它包含状态码、消息提示以及数据字段。

weixin_42589700的博客 747

【MyBatisPlus】MyBatisPlus 增删改查 (三)

1. CURD方法参数与返回值说明1.1 方法参数3.2 返回值4. BaseMapper CURD接口4.1 查4.2 增加4.3 修改4.4 删除5. ServiceImpl CURD接口5.1 Get查询单条记录5.2 List查询多条记录5.3 Count查询记录数5.4 save新增数据5.4 update修改数据 1. CURD方法参数与返回值说明 理解了方法参数与返回值,各个增删改查方法都是大同小异,都是各种重载方法。 1.1 方法参数 @Param(Constants.WRAPPER.

Duson 2260

Spring Boot集成Swagger与MyBatisPlus的数据库操作优化

Spring Boot是由Pivotal团队提供的全新框架,旨在简化Spring应用的初始搭建以及开发过程。其设计目的是为了减少配置文件的数量(约定优于配置),快速启动项目,并提供生产级别的Spring应用。Swagger是一个规范且完整的框架,用于设计、构建、记录以及使用RESTful Web服务。简单地说,Swagger可以帮助我们设计清晰的API文档,并且在这个基础上进行维护和使用,使得前后端分离的开发模式更加顺畅。

weixin_31597759的博客 985

MybatisPlus中@TableField注解的使用

场景 项目搭建专栏: https://blog.youkuaiyun.com/BADAO_LIUMANG_QIZHI/column/info/37194 基础搭建: https://blog.youkuaiyun.com/BADAO_LIUMANG_QIZHI/article/details/89407994 实现 官方文档说明: com.baomidou.mybatisplus.annotations.T...

BADAO_LIUMANG_QIZHI的博客 9万+

【关于四足机器人那些事】足端轨迹规划-八次多项式轨迹

系列文章目录 文章目录系列文章目录前言一、多项式曲线二、八次多项式曲线总结 前言 在四足机器人的研究中,有一个很关键的问题,就是如何减少足端在触地瞬间的冲击,避免把机器人把自己给蹬倒了?这时候就需要一个合理的足端轨迹规划。本篇将会介绍几种足端轨迹。 本文将对四足机器人的足端轨迹进行规划。将数学中的复合摆线和多项式曲线引入到足端轨迹的规划中,根据零冲击原则[2],规划出 3 条满足要求的足端轨迹,包括: 复合摆线轨迹 八次多项式轨迹 分段五次多项式轨迹 本篇先介绍 - 八次多项式轨迹 一、多项式曲

LiuZ的博客 2954

Multisim新手必看:从零搭建数字时钟仿真电路(附完整原理图)

本文详细介绍了如何使用Multisim从零开始搭建数字时钟仿真电路,涵盖晶振电路设计、计数电路实现、校时功能配置等关键步骤。通过完整的原理图和实用技巧,帮助新手快速掌握Multisim仿真设计,实现精准的数字时钟功能。

ios99的博客 328

MyBatis-Plus @TableField详解

【代码】MyBatis-Plus @TableField详解。

qq_58148854的博客 1639

RK3576+IMX415 MIPI摄像头零拷贝显示系统

MIPI CSI-2是嵌入式视觉系统中主流的高速图像传感器接口标准,其核心价值在于低延迟、高带宽与硬件级DMA直通能力。基于V4L2子系统与DRM/KMS驱动栈,可构建从传感器RAW数据到帧缓冲区的零拷贝通路,显著降低CPU负载并提升实时性。该技术广泛应用于工业检测、边缘AI推理前数据接入及多路同步采集等场景。本文以Rockchip RK3576 SoC和索尼IMX415传感器为典型组合,详解MIPI物理层适配、内核驱动集成、GStreamer零拷贝管道搭建及systemd服务化部署,覆盖从硬件信号完整性到

weixin_36047538的博客 216

SQL 条件查询

按条件表达式 > < = != <> >= <= 其中!= <> 意思一样,都是不等于,建议用 <> 逻辑表达式 && || ! and or not 模糊查询 like between and in is null # 查看name第3个字符为n,第...

tian_ya_jian_ke的博客 386

PCL 欧式聚类(C++详细过程版)

为充分了解算法实现的每一个细节和有待改进的地方,使用C++代码对算法实现过程进行复现。

点云侠的博客 2447

华为OD机考双机位C卷 - 最左侧冗余覆盖子串 (Java)

华为OD机考双机位C卷 - 最左侧冗余覆盖子串 (Java), 提供Java、C++、Python、Go、JavaScript源码实现,并提供完整思路讲解,以及在线OJ模拟做题。

算法大师! 58

MybatisPlus @TableField之SqlCondition源码解析

MybatisPlus @TableField之SqlCondition

unimme的专栏 542

YOLO11全网首发优化:卷积魔改创新 | AAAI 2025 | 一种新颖的风车形卷积(PConv)符合微弱小目标的像素高斯空间分布,增强特征提取,显著增加接受野

我们提出了一种新颖的风车形卷积(PConv)作为骨干网络下层标准卷积的替代品。PConv能更好地符合微弱小目标的像素高斯空间分布,增强特征提取,显著增加接受野,且只引入最小的参数增加。

①答疑群聊服务;②YOLO大模型知识问答系统;③计算机视觉论文生成智能体; 1972

Spring boot 3集成mybatisplus

spring版本:3.2.10jdk版本:21。

c3214401899的博客 533

(数字图像处理MATLAB+Python)第五章图像增强-第一节:图像增强概述和基于灰度级变换的图像增强

图像增强(Image Enhancement):指不考虑图像降质原因,利用各种数学方法和变换手段,增强图像中人们感兴趣部分或提高有用的图像特征的清晰度。从图像质量来看,图像增强提高了图像的可懂度,改善了图像的视觉效果例如在现实场景中,针对那些对比度较差、视觉效果不好的图像,我们就可以利用图像增强改善视觉质量图像增强可分为如下几种基于灰度级变换的图像增强基于直方图修正的图像增强基于照度反射模型的图像增强基于模糊技术的图像增强基于伪彩色处理的图像增强其他图像增强方法分段线性灰度级变换。

快乐江湖的博客 3331

Sigrity System Explorer Transient Analysis模式进行瞬态仿真分析操作指导-单端信号-串联端接

Sigrity System Explorer Transient Analysis模式可以用于瞬态仿真分析,通过搭建简易拓扑用于前仿真分析通道的时域性能,下面搭建一个简易的单端拓扑并且进行串联端接,以下图为例,准备好发送接收端的IBIS模型, (se_example.ibs,本例发送接收端都使用相同的IBIS模型),以及传输线的S参数模型(W1_welement_se.sp)最上方的图形界面是传输线的模型,本例是一个上下都有参考平面的带状线,右侧的梯形是蚀刻角度,根据W1和W2以及铜厚来确定。

weixin_54787054的博客 338

MyBatisPlus与Spring Boot集成源码分析

本文深入解析MyBatisPlus与Spring Boot的集成原理,重点剖析自动配置机制和Mapper扫描机制。通过自动配置类MybatisPlusAutoConfiguration实现数据源、SqlSessionFactory等核心组件的自动装配,同时借助@MapperScan注解完成Mapper接口的扫描与代理生成。文章提供了完整的集成示例,包括项目搭建、配置文件设置、Mapper接口定义以及业务层实现,帮助开发者快速掌握集成方法并解决常见问题。

fykam的博客 941

汉书HE8,好用的汇编代码编写工具

汉书HE8,好用的汇编代码编写工具早期编写汇编代码所用功能强大

Spring Boot是什么?MybatisPlus常用注解,LambdaQueryWrapper常用方法

Spring Boot是什么?MybatisPlus常用注解,LambdaQueryWrapper常用方法

hutao8896的博客 1201

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

廖雪峰Python教程[完整版]

廖雪峰的python教程整理的,已经排好版了,而且还是完整的,适合小白

spring boot集成druid连接池+mybatisPlus

在后端生产环境中,每次查询都要连接一次数据库,这是不切实际的,会给数据库带来很大压力,这时使用连接池就是一个很好的方法。而mybatisPuls在springboot查询数据库中使用可以大大降低工作量,这两者结合在性能和效率上可以说很香了。 Druid介绍 Druid首先是一个数据库连接池。Druid是目前最好的数据库连接池,在功能、性能、扩展性方面,都超过其他数据库连接池,包括DBCP、C3P0、BoneCP、Proxool、JBoss DataSource。 Druid已经在阿里巴巴部署了超过上千

异世者的博客 2693

MybatisPlus分页插件(Spring boot3, MybatisPlus 3.5.9+)

官方对插件设置为可选项, 因此还需要引入一个依赖,和另一个。首先引入MybatisPlus 的依赖,因为选取的MybatisPlus 是。

qq_75045333的博客 1422

MyBatisPlus整合Spring Boot管理用户语音生成任务

在AI语音快速发展的背景下,如何稳定高效地管理语音合成任务成为关键。通过MyBatisPlus与Spring Boot整合,实现任务的持久化、异步处理和状态追踪,支撑高并发场景下的用户需求。系统支持音色克隆、情感控制等高级功能,同时保障幂等性、安全性和存储效率,已在短视频、虚拟人等场景落地验证。

weixin_29443363的博客 989

spring boot集成mybatisplus

1、创建工程,勾选lambok、spring web、MySQL driver等依赖。 2、添加mybais plus依赖 <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.3.4.RELEASE</version>

JavaScript入门 199

【亲测免费】 SpringBoot_MyBatisPlus:基于Spring Boot和MyBatisPlus的开源项目

SpringBoot_MyBatisPlus 是一个开源项目,主要使用 Java 编程语言开发,它基于 Spring Boot 框架,集成了 MyBatisPlus 持久层框架。该项目旨在提供一个高效、易用的开发基础平台,使得开发者能够更加便捷地进行后台系统的构建。 ## 2. 项目核心功能 - **核心框架:** 采用 Spring Boot 1.5.1,提供快速开发的能力,简化了配置工作。...

gitblog_01134的博客 1011

spring boot mybatisplus集成_Mybatisplus一对一、一对多、多对一、多对多映射

一、MybatisPlus介绍我用简短的话概括一下,mybatisplus是对mybatis框架的二次封装,功能可谓是非常的强大,简单的CRUD几乎不需要再去写DAO层,即可实现.MybatisPlus是Mybatis的增强工具,在Mybatis的基础上只做增强不做修改,为简化开发、提高效率而生.好处多多!二、MybatisPlus开发环境搭建开发环境:IDEA2019.2SpringB...

weixin_39835925的博客 2140

spring boot 整合mybatisPlus-Generator Swagger

第一步 导入依赖 <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.4.0</version> </dependency> <-- 自动代码生成器模板--> <dependency> <g

l1306395862的博客 504

Spring boot整合MybatisPlus:一个基本的demo

使用Spring Initializr方式快速初始化一个Spring boot项目! 1、IDEA—>File—>new project—>Spring Initializr: 2、点next,完善项目信息: 3、next 后选择项目依赖: Tools ==》DevTools、Lombok Web ==》Spring Web SQL ==》MySQL Driver、JDBC 4、next,填写项目名,指定项目生成地址 —> finish 5、打开刚刚创建Module的p

qq_44440275的博客 420
上一篇: Spring boot JPA
xiaoduup
博客等级 码龄9年 23粉丝 83原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值