mybatis-plus中常用的注解
常用的注解:
@TableName:对数据表名注解 @TableId:表主键标识 @TableId(value = "id", type = IdType.AUTO):自增 @TableId(value = "id", type = IdType.ID_WORKER_STR):分布式全局唯一ID字符串类型 @TableId(value = "id", type = IdType.INPUT):自行输入 @TableId(value = "id", type = IdType.ID_WORKER):分布式全局唯一ID 长整型类型 @TableId(value = "id", type = IdType.UUID):32位UUID字符串 @TableId(value = "id", type = IdType.NONE):无状态 @TableField:表字段标识 @TableField(exist = false):表示该属性不为数据库表字段,但又是必须使用的。 @TableField(exist = true):表示该属性为数据库表字段。 @TableField(condition = SqlCondition.LIKE):表示该属性可以模糊搜索。 @TableField(fill = FieldFill.INSERT):注解填充字段 ,生成器策略部分也可以配置! @FieldStrategy: @FieldFill @Version:乐观锁注解、标记 @EnumValue:通枚举类注解 @TableLogic:表字段逻辑处理注解(逻辑删除) @SqlParser:租户注解 @KeySequence:序列主键策略
常用的就三个:@TableName @TableId @TableField

全局ID生成策略:
在全局配置文件中: 就不需要再每个Pojo主键上配置了: mybatis-plus: global-config: db-config: id-type: auto
逻辑删除:
需要添加逻辑删除的字段 局部单表逻辑删除,需要在对应的pojo类加入对应的逻辑删除标识字段 @TableLogic // 代表逻辑删除 private Integer flag; public Integer getFlag() { return flag; }
全局逻辑删除配置, 如果进行了全局逻辑删除配置并且指定了,就可以不用在每个pojo类中配置了@TableLogic 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)

当执行删除, 将会把逻辑删除字段进行修改


当执行查询,会自动查询有效数据 where flag=1


执行 SQL 分析打印:
<dependency> <groupId>p6spy</groupId> <artifactId>p6spy</artifactId> <version>最新版本</version> </dependency>

添加p6spy : 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
sql 日志美化插件:



数据安全保护:防止删库跑路
1.得到16位随机秘钥 @Test void test(){// 生成 16 位随机 AES 密钥 String randomKey = AES.generateRandomKey(); System.out.println(randomKey); } da12166c7db8a58f
2.根据秘钥加密 数据库连接信息 @Test void test(){ String url = AES.encrypt("jdbc:mysql://localhost:3306/mybatisplus?characterEncoding=utf8&useSSL=false&serverTimezone=UTC&" , "da12166c7db8a58f"); String uname = AES.encrypt("root" , "da12166c7db8a58f"); String pwd = AES.encrypt("123456" , "da12166c7db8a58f"); System.out.println(url); System.out.println(uname); System.out.println(pwd); }

3.修改配置文件 注意要mpw:开头 username: mpw:0Cj49ihj1Q6UbkRfixFdVg== password: mpw:yp192XvO1C0jq67MeCvlIg== url: mpw:nIh0E63gBfvpFbz2tXDyWDN2kFpD+apc9JaRYosGY5sKL3zyNwalK3OfGo27p8AM8BL0llHGFwpfdELaf79NIxm8kfOMhUdOFLNy7g85BTCrEzbYEHqp3THf7KOz80Ka
4.在部署的时候需要解密
java -jar xxxx.jar --mpw.key=你的16位随机秘钥, 越少人知道越好
乐观锁使用MyBatisPlus的解决方式:
由于锁这个字眼我们需要在数据库加个字段“version”来控制版本 在类中加个属性
@Version //这就是控制版本的 @TableField(fill = FieldFill.INSERT) //这个方便在添加的时候设置版本初始为1 private Integer version; //版本的字段
下面这个也是MyBatisPlus的一个插件 只需要实现MetaObjectHandler就可以了
@Component public class MyMetaObjectHandler implements MetaObjectHandler { @Override public void insertFill(MetaObject metaObject) { //这里的“version”就是指定的字段,设置初始值为1,之后每修改一次+1 this.setFieldValByName("version",1,metaObject); } @Override public void updateFill(MetaObject metaObject) { } }
在MyBatis中存在一个乐观锁插件: OptimisticLockerInnerInterceptor
@Configuration @MapperScan("com.lzz.mapper") public class MyConfig { //乐观锁插件 @Bean public OptimisticLockerInterceptor optimisticLockerInterceptor(){ return new OptimisticLockerInterceptor(); } }
接下来在做增加数据的时候,调用insert添加方法就可以了。
修改的时候呢,我们需要先查人后再做修改,因为我们为了防止问题的发生,需要先去查询版本号比对才进行后续操作!!
代码生成器:
package com.tulingxueyuan; 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.InjectionConfig; import com.baomidou.mybatisplus.generator.config.*; import com.baomidou.mybatisplus.generator.config.po.LikeTable; 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 java.util.ArrayList; import java.util.List; import java.util.Scanner; /*** * @Author 徐庶 QQ:1092002729 * @Slogan 致敬大师,致敬未来的你 * * pms_product */ public class GeneratorApp { /** * <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) { String moduleName = scanner("模块名"); String tableName = scanner("表名(多个用,号分隔,或者按前缀(pms*))"); String prefixName = scanner("需要替换的表前缀"); // 代码生成器 AutoGenerator mpg = new AutoGenerator(); // 全局配置 GlobalConfig gc = new GlobalConfig(); // 获得当前项目的路径 String projectPath = System.getProperty("user.dir")+"/05_generator"; // 设置生成路径 gc.setOutputDir(projectPath + "/src/main/java"); // 作者 gc.setAuthor("xushu"); // 代码生成是不是要打开所在文件夹 gc.setOpen(false); // 生成Swagger2注解 gc.setSwagger2(true); // 会在mapper.xml 生成一个基础的<ResultMap> 映射所有的字段 gc.setBaseResultMap(true); // 同文件生成覆盖 gc.setFileOverride(true); //gc.setDateType(DateType.ONLY_DATE) // 实体名:直接用表名 %s=表名 gc.setEntityName("%s"); // mapper接口名 gc.setMapperName("%sMapper"); // mapper.xml 文件名 gc.setXmlName("%sMapper"); // 业务逻辑类接口名 gc.setServiceName("%sService"); // 业务逻辑类实现类名 gc.setServiceName("%sImplService"); // 将全局配置设置到AutoGenerator mpg.setGlobalConfig(gc); // 数据源配置 DataSourceConfig dsc = new DataSourceConfig(); dsc.setUrl("jdbc:mysql://localhost:3306/tuling_mall?characterEncoding=utf8&useSSL=false&serverTimezone=UTC&"); dsc.setDriverName("com.mysql.cj.jdbc.Driver"); dsc.setUsername("root"); dsc.setPassword("123456"); mpg.setDataSource(dsc); // 包配置 PackageConfig pc = new PackageConfig(); // 模块名 pc.setModuleName(moduleName); // 包名 pc.setParent("com.tulingxueyuan"); // 完整的报名: com.tulingxueyuan.pms mpg.setPackageInfo(pc); // 自定义配置 InjectionConfig cfg = new InjectionConfig() { @Override public void initMap() { // to do nothing } }; // 如果模板引擎是 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; } }); cfg.setFileOutConfigList(focList); mpg.setCfg(cfg); // 配置模板 TemplateConfig templateConfig = new TemplateConfig(); // 把已有的xml生成置空 templateConfig.setXml(null); mpg.setTemplate(templateConfig); // 策略配置 StrategyConfig strategy = new StrategyConfig(); // 表名的生成策略:下划线转驼峰 pms_product -- PmsProduct strategy.setNaming(NamingStrategy.underline_to_camel); // 列名的生成策略:下划线转驼峰 last_name -- lastName strategy.setColumnNaming(NamingStrategy.underline_to_camel); //strategy.setSuperEntityClass("你自己的父类实体,没有就不用设置!"); //strategy.setEntityLombokModel(true); // 在controller类上是否生成@RestController strategy.setRestControllerStyle(true); // 公共父类 //strategy.setSuperControllerClass("你自己的父类控制器,没有就不用设置!"); if(tableName.indexOf('*')>0){ // 按前缀生成表 strategy.setLikeTable(new LikeTable(tableName.replace('*','_'))); } else{ // 要生成的表名 多个用逗号分隔 strategy.setInclude(tableName); } // 设置表替换前缀 strategy.setTablePrefix(prefixName); // 驼峰转连字符 比如 pms_product --> controller @RequestMapping("/pms/pmsProduct") //strategy.setControllerMappingHyphenStyle(true); mpg.setStrategy(strategy); // 进行生成 mpg.execute(); } }

浙公网安备 33010602011771号