springboot整合MyBatis-Plus(八)

MyBatis-Plus官网文档: https://mp.baomidou.com/
学习视频推荐:
慕课网: https://www.imooc.com/video/20094
狂神说: https://www.bilibili.com/video/BV17E411N7KN

引入依赖

			<!-- 引入阿里数据库连接池 -->
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid</artifactId>
                <version>1.1.6</version>
            </dependency>
            <!--mybatis-->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>8.0.21</version>
            </dependency>
            <dependency>
                <groupId>p6spy</groupId>
                <artifactId>p6spy</artifactId>
                <version>3.9.1</version>
            </dependency>
            <dependency>
                <groupId>com.baomidou</groupId>
                <artifactId>mybatis-plus-boot-starter</artifactId>
                <version>3.4.2</version>
            </dependency>
            <dependency>
                <groupId>com.baomidou</groupId>
                <artifactId>mybatis-plus-core</artifactId>
                <version>3.4.2</version>
            </dependency>
            <dependency>
                <groupId>com.baomidou</groupId>
                <artifactId>mybatis-plus-generator</artifactId>
                <version>3.4.1</version>
            </dependency>
            <dependency>
                <groupId>org.freemarker</groupId>
                <artifactId>freemarker</artifactId>
                <version>2.3.30</version>
            </dependency>
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <version>1.18.8</version>
            </dependency>
            <!-- swagger2 -->
            <dependency>
                <groupId>io.swagger</groupId>
                <artifactId>swagger-annotations</artifactId>
                <version>1.5.22</version>
            </dependency>
            <dependency>
                <groupId>com.github.xiaoymin</groupId>
                <artifactId>knife4j-spring-boot-starter</artifactId>
                <version>2.0.4</version>
            </dependency>

配置分页和乐观锁插件

import com.baomidou.mybatisplus.autoconfigure.ConfigurationCustomizer;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@MapperScan("com.xx.xxx")
@EnableTransactionManagement
@Configuration 
public class MyBatisPlusConfig {

    /**
     * 新的分页插件
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
        //乐观锁
        mybatisPlusInterceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        //分页配置
        mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor());
        return mybatisPlusInterceptor;
    }

    /**
     * 新的分页插件,一缓和二缓遵循mybatis的规则,需要设置 MybatisConfiguration#useDeprecatedExecutor = false 避免缓存出现问题(该属性会在旧插件移除后一同移除)
     */
    @Bean
    public ConfigurationCustomizer configurationCustomizer() {
        return configuration -> configuration.setUseDeprecatedExecutor(false);
    }


}

配置自动填充功能

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 自动填充功能
 */
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    /**
     * 插入时的填充策略
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        this.setFieldValByName("createTime",new Date(),metaObject);
        this.setFieldValByName("updateTime",new Date(),metaObject);
    }

    /**
     * 更新时的填充策略
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        this.setFieldValByName("updateTime",new Date(),metaObject);
    }
}

yml配置执行 SQL 分析打印,mybatis-plus基础设置

注意:

需要在 druid.filters 配置中去掉 wall 或者启动会报错!!!!!

druid:
      # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
      # filters: stat,wall
      filters: stat
spring:
  datasource:
      username: root
      password: root
      #url: jdbc:mysql://localhost:3306/user?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
      #driver-class-name: com.mysql.cj.jdbc.Driver
      # 应在测试环境下开启 依赖 p6spy 组件,完美的输出打印 SQL 及执行时长
      driver-class-name: com.p6spy.engine.spy.P6SpyDriver
      url: jdbc:p6spy:mysql://localhost:3306/user?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
      dbType: mysql
      type: com.alibaba.druid.pool.DruidDataSource
      

mybatis-plus:
    # xml扫描,多个目录用逗号或者分号分隔(告诉 Mapper 所对应的 XML 文件位置)
    mapper-locations: classpath:mapper/*.xml,classpath*:com/zm/mapper/xml/*Mapper.xml
    type-aliases-package: com.zm.entity
    global-config:
      db-config:
        logic-delete-field: deleted  # 全局逻辑删除的实体字段名(since 3.3.0,配置后可以忽略不配置步骤2)
        logic-delete-value: 1 # 逻辑已删除值(默认为 1)
        logic-not-delete-value: 0 # 逻辑未删除值(默认为 0)
    configuration:
        # 是否开启自动驼峰命名规则映射:从数据库列名到Java属性驼峰命名的类似映射
        map-underscore-to-camel-case: true
        # 如果查询结果中包含空值的列,则 MyBatis 在映射的时候,不会映射这个字段
        call-setters-on-nulls: true
        # 这个配置会将执行的sql打印出来,在开发或测试的时候可以用
        log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

CodeGenerator代码生成器

关闭生成Service,ServiceImpl 和Controller,如需打开注释 templateConfig下的设置
生成目录地址可修改指定位置,需自己修改 projectPath

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableFill;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;

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

public class CodeGenerator {

    /**
     * <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:\\project\\zm\\core\\";// 想生成的生成的代码路径
        gc.setOutputDir(projectPath + "/src/main/java");
        gc.setAuthor("zhoum");
        gc.setOpen(false); //生成后是否打开资源管理器
        gc.setFileOverride(false); //重新生成时文件是否覆盖
        gc.setEntityName("%sEntity");
        gc.setServiceName("%sService");
        gc.setIdType(IdType.ASSIGN_ID); //主键策略(Mybatis-plus中有描述)
        gc.setDateType(DateType.ONLY_DATE);//定义生成的实体类中日期类型
        gc.setSwagger2(true);//实体属性 Swagger2 注解
        mpg.setGlobalConfig(gc);
        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://localhost:3306/xxxx?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8");
        // dsc.setSchemaName("public");
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("xxxxxxx");
        dsc.setDbType(DbType.MYSQL);
        mpg.setDataSource(dsc);
        // 包配置
        PackageConfig pc = new PackageConfig();
        //pc.setModuleName(scanner("模块名"));
        pc.setParent("com.zm");
        mpg.setPackageInfo(pc);
        // 如果模板引擎是 freemarker
        String templatePath = "/templates/mapper.xml.ftl";
        // 如果模板引擎是 velocity
        //String templatePath = "/templates/mapper.xml.vm";
        // 自定义输出配置
        List<FileOutConfig> focList = new ArrayList<>();
        // 自定义配置会被优先输出
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
                return projectPath + "/src/main/resources/mapper/" + pc.getModuleName()
                        + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });
        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();
        // 配置自定义输出模板
        //指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
        templateConfig.setService(null);// 关闭生成Service
        templateConfig.setController(null);// 关闭生成Controller
        templateConfig.setServiceImpl(null);// 关闭生成ServiceImpl
        mpg.setTemplate(templateConfig);
        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);// 数据库表映射到实体的命名策略
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);// 数据库表字段映射到实体的命名策略, 未指定按照 naming 执行
        // 自动填充配置
        TableFill gmtCreate = new TableFill("create_time", FieldFill.INSERT);
        TableFill gmtModified = new TableFill("update_time", FieldFill.INSERT_UPDATE);
        ArrayList<TableFill> tableFills = new ArrayList<>();
        tableFills.add(gmtCreate);
        tableFills.add(gmtModified);
        strategy.setTableFillList(tableFills);
        // 乐观锁
        strategy.setVersionFieldName("version");// 乐观锁属性名称
        strategy.setLogicDeleteFieldName("deleted");//逻辑删除属性名称
        strategy.setEntityLombokModel(true);// Lombok 开启
        strategy.setRestControllerStyle(true);// restControllerStyle
        // 公共父类
        //strategy.setSuperEntityClass("你自己的父类实体,没有就不用设置!");
        //strategy.setSuperControllerClass("你自己的父类控制器,没有就不用设置!");
        // 写于父类中的公共字段
        //strategy.setSuperEntityColumns("id");
        strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));// 需要包含的表名
        strategy.setControllerMappingHyphenStyle(true);// 开启驼峰转连字符
        strategy.setTablePrefix(pc.getModuleName() + "_");// 表前缀
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }


}

数据表及测试代码

-- ----------------------------
-- Table structure for `label`
-- ----------------------------
DROP TABLE IF EXISTS `label`;
CREATE TABLE `label` (
  `id` int(4) NOT NULL AUTO_INCREMENT COMMENT 'ID',
  `name` varchar(32) DEFAULT NULL COMMENT '名称',
  `sort` int(4) DEFAULT NULL COMMENT '排序号',
  `version` tinyint(4) DEFAULT '1' COMMENT '乐观锁',
  `deleted` tinyint(1) DEFAULT '0',
  `create_time` datetime DEFAULT NULL COMMENT '创建时间',
  `update_time` datetime DEFAULT NULL COMMENT '更新时间',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=19 DEFAULT CHARSET=utf8mb4 COMMENT='学生信息表';
-- ----------------------------
-- Records of label
-- ----------------------------
INSERT INTO `label` VALUES ('16', '4更新成功,我就插你3的队', '0', '3', '0', '2021-02-03 21:54:47', '2021-02-03 22:04:12');
INSERT INTO `label` VALUES ('17', '测试插入填充字段', '1', '1', '0', '2021-02-03 21:54:49', '2021-02-03 21:55:01');
INSERT INTO `label` VALUES ('18', '测试插入填充字段', '2', '1', '0', '2021-02-03 21:13:38', '2021-02-03 21:13:38');
import com.zm.dao.UserDao;
import com.zm.entity.LabelEntity;
import com.zm.manager.redis.RedisUtil;
import com.zm.mapper.LabelMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;


@SpringBootTest
class WebApplicationTests {

    @Autowired
    private LabelMapper labelMapper;

    @Test
    void test() {

        // 测试插入填充字段
//        LabelEntity labelEntity1 = new LabelEntity();
//        labelEntity1.setName("测试插入填充字段");
//        labelMapper.insert(labelEntity1);

        // 测试更新填充字段
        // 测试乐观锁是否成功 先查询乐观锁 更新时带上乐观锁参数 否则乐观锁失效
        LabelEntity labelEntity = labelMapper.selectById(16);
        Integer version = labelEntity.getVersion();
        LabelEntity labelEntity3 = new LabelEntity();
        labelEntity3.setId(16);
        labelEntity3.setVersion(version);
        labelEntity3.setName("3更新成功");

        LabelEntity labelEntity4 = new LabelEntity();
        labelEntity4.setId(16);
        labelEntity4.setVersion(version);
        labelEntity4.setName("4更新成功,我就插你3的队");
        labelMapper.updateById(labelEntity4);

        int i = labelMapper.updateById(labelEntity3);
        if(i==0){
            System.out.println("3更新失败");
        }

        // 测试list是否成功
        // labelMapper.selectList(null).forEach(System.out::println);

        // 测试分页是否成功
//        Page page = labelMapper.selectPage(new Page(1,2), null);
//        page.getRecords().forEach(System.out::println);


    }


}

配置打印具体sql

链接: 执行 SQL 分析打印.

在这里插入图片描述

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=org.h2.Driver
# 是否开启慢SQL记录
outagedetection=true
# 慢SQL记录标准 2 秒
outagedetectioninterval=2

mybatis 使用注意

映射文件中,if标签判断字符串相等

正确用法
<if test="sex=='Y'.toString()"></if>
<if test = 'sex== "Y"'>
错误用法
<if test="sex=='Y'"></if>

使用#{},而不是${}

用XML注释取代SQL注释

当传递多个参数时

在mapper接口中,一定要注明:@Param(“email”)注解,否则报错。
例:

List selectById(@Param(“id”)String id,@Param(“sex”)Byte sex);

转义符

 在mybatis中这种符号将不会解析。
<![CDATA[ when min(starttime)<='12:00' and max(endtime)<='12:00' ]]>   

使用批量操作

        <if test="ids != null and ids.size() != 0">
            and id IN (
            <foreach collection="ids" item="item" separator=",">
                #{item}
            </foreach>
            )
        </if>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值