关于MybatisPlus使用Generator自动生成代码的实现(包含创建时间和更新时间的自动填充)
- 基于springboot的基础上添加以下依赖
<dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-extension</artifactId><version>3.4.3</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency><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><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId><!-- 排除 默认使用的logback --><exclusions><exclusion><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-logging</artifactId></exclusion></exclusions></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-log4j2</artifactId></dependency>
- 添加Generator代码生成器配置如下(注:需要根据自己的环境完成配置)
package com.companyname.db.generator;import com.baomidou.mybatisplus.annotation.FieldFill; 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.TableFill; import com.baomidou.mybatisplus.generator.config.rules.FileType; import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;import java.io.File; import java.util.ArrayList; import java.util.List;public class Generator {public static void main(String[] args) {// 代码生成器AutoGenerator mpg = new AutoGenerator();// 全局配置GlobalConfig gc = new GlobalConfig();String projectPath = System.getProperty("user.dir");gc.setOutputDir(projectPath + "/项目名/src/main/java");gc.setOpen(false);gc.setAuthor("");// gc.setSwagger2(true); 实体属性 Swagger2 注解mpg.setGlobalConfig(gc);// 数据源配置DataSourceConfig dsc = new DataSourceConfig();dsc.setUrl("jdbc:mysql://192.168.*.*:*/*?useUnicode=true&useSSL=false&characterEncoding=utf8");dsc.setDriverName("com.mysql.cj.jdbc.Driver");dsc.setUsername("数据库账号");dsc.setPassword("数据库密码");mpg.setDataSource(dsc);// 包配置PackageConfig pc = new PackageConfig();pc.setModuleName("db");pc.setParent("com.companyname");pc.setEntity("domain");pc.setMapper("dao");mpg.setPackageInfo(pc);// 注入自定义配置,可以在 VM 中使用 cfg.abc 【可无】InjectionConfig cfg = new InjectionConfig() {@Overridepublic void initMap() {}};List<FileOutConfig> focList = new ArrayList<FileOutConfig>();// 调整 xml生成目录演示/*focList.add(new FileOutConfig("/templates/mapper.xml.vm") {@Overridepublic String outputFile(TableInfo tableInfo) {return projectPath + "/src/main/resources/mapper/" + pc.getModuleName()+ "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;}});*/cfg.setFileCreate((configBuilder, fileType, filePath) -> {//如果是Entity则直接返回true表示写文件if (fileType == FileType.ENTITY) {return true;}//否则先判断文件是否存在File file = new File(filePath);boolean exist = file.exists();if (!exist) {file.getParentFile().mkdirs();}//文件不存在或者全局配置的fileOverride为true才写文件return !exist || configBuilder.getGlobalConfig().isFileOverride();});cfg.setFileOutConfigList(focList);mpg.setCfg(cfg);// 自定义模板配置,可以 copy 源码 mybatis-plus/src/main/resources/templates 下面内容修改,// 放置自己项目的 src/main/resources/templates 目录下, 默认名称一下可以不配置,也可以自定义模板名称TemplateConfig tc = new TemplateConfig();tc.setService(null);tc.setServiceImpl(null);tc.setEntity("entity.java"); //domaintc.setMapper("mapper.java");tc.setController(null);tc.setXml(null);// 策略配置StrategyConfig strategy = new StrategyConfig();//设置命名规则(驼峰式)strategy.setNaming(NamingStrategy.underline_to_camel);//设置表列命名规则(驼峰式)strategy.setColumnNaming(NamingStrategy.underline_to_camel);//设置entity父类 // strategy.setSuperEntityClass(BaseEntity.class);//设置lombok(看个人习惯)strategy.setEntityLombokModel(true);//是否生成@Resetcontrollerstrategy.setRestControllerStyle(false);//为create_time和update_time字段添加自动填充注解List tableFillList=new ArrayList();tableFillList.add(new TableFill("create_time", FieldFill.INSERT));tableFillList.add(new TableFill("update_time",FieldFill.INSERT_UPDATE));strategy.setTableFillList(tableFillList);// 公共父类//strategy.setSuperControllerClass("你自己的父类控制器,没有就不用设置!");// 写于父类中的公共字段 // strategy.setSuperEntityColumns(new String[]{"id", "deleted", "create_time", "update_time"});//设置需要生成的表strategy.setInclude(new String[]{"tb_a","tb_b","tb_c",});strategy.setEntitySerialVersionUID(false);strategy.setEntityColumnConstant(false);//strategy.setControllerMappingHyphenStyle(true);//设置映射时,实体类与真实表名的头部忽略strategy.setTablePrefix("tb_");//是否生成表中字段的@TableField注解strategy.setEntityTableFieldAnnotationEnable(false);mpg.setStrategy(strategy);// 如上任何一个模块如果设置 空 OR Null 将不生成该模块。mpg.setTemplate(tc);// 执行生成mpg.execute();} }
- 添加domain和dao的模板(entity.java.vm和mapper.java.vm)到resources下
entity.java.vm
package ${package.Entity};#foreach($pkg in ${table.importPackages}) import ${pkg}; #end #if(${swagger2}) import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; #end #if(${entityLombokModel}) import lombok.Data; import lombok.EqualsAndHashCode;#if(${chainModel})import lombok.experimental.Accessors;#end #end/*** @Description ${entity}* @Author ${author}* @Date ${date}* @Version 2.1*/ #if(${entityLombokModel}) @Data#if(${superEntityClass}) @EqualsAndHashCode(callSuper = true)#else @EqualsAndHashCode(callSuper = false)#end#if(${chainModel}) @Accessors(chain = true)#end #end #if(${table.convert}) @TableName("${table.name}") #end #if(${swagger2}) @ApiModel(value="${entity}对象", description="$!{table.comment}") #end #if(${superEntityClass}) public class ${entity} extends ${superEntityClass}#if(${activeRecord})<${entity}>#end { #elseif(${activeRecord}) public class ${entity} extends Model<${entity}> { #else public class ${entity} implements Serializable { #end#if(${entitySerialVersionUID})private static final long serialVersionUID = 1L; #end ## ---------- BEGIN 字段循环遍历 ---------- #foreach($field in ${table.fields})#if(${field.keyFlag}) #set($keyPropertyName=${field.propertyName}) #end #if("$!field.comment" != "")#if(${swagger2})@ApiModelProperty(value = "${field.comment}")#else/*** ${field.comment}*/#end #end #if(${field.keyFlag}) ## 主键#if(${field.keyIdentityFlag})@TableId(value = "`${field.annotationColumnName}`", type = IdType.AUTO)#elseif(!$null.isNull(${idType}) && "$!idType" != "")@TableId(value = "`${field.annotationColumnName}`", type = IdType.${idType})#elseif(${field.convert})@TableId("`${field.annotationColumnName}`")#end ## 普通字段 #elseif(${field.fill}) ## ----- 存在字段填充设置 -----#if(${field.convert})@TableField(value = "`${field.annotationColumnName}`", fill = FieldFill.${field.fill})#else@TableField(fill = FieldFill.${field.fill})#end #elseif(${field.convert})@TableField("`${field.annotationColumnName}`") #end ## 乐观锁注解 #if(${versionFieldName}==${field.name})@Version #end ## 逻辑删除注解 #if(${logicDeleteFieldName}==${field.name})@TableLogic #endprivate ${field.propertyType} ${field.propertyName}; #end ## ---------- END 字段循环遍历 ----------#if(!${entityLombokModel}) #foreach($field in ${table.fields})#if(${field.propertyType.equals("boolean")})#set($getprefix="is")#else#set($getprefix="get")#endpublic ${field.propertyType} ${getprefix}${field.capitalName}() {return ${field.propertyName};}#if(${chainModel})public ${entity} set${field.capitalName}(${field.propertyType} ${field.propertyName}) {#elsepublic void set${field.capitalName}(${field.propertyType} ${field.propertyName}) {#endthis.${field.propertyName} = ${field.propertyName};#if(${chainModel})return this;#end} #end ## --foreach end--- #end ## --end of #if(!${entityLombokModel})--#if(${entityColumnConstant})#foreach($field in ${table.fields})public static final String ${field.name.toUpperCase()} = "`${field.name}`";#end #end #if(${activeRecord})@Overrideprotected Serializable pkVal() {#if(${keyPropertyName})return this.${keyPropertyName};#elsereturn null;#end}#end #if(!${entityLombokModel})@Overridepublic String toString() {return "${entity}{" +#foreach($field in ${table.fields})#if($!{foreach.index}==0)"${field.propertyName}=" + ${field.propertyName} +#else", ${field.propertyName}=" + ${field.propertyName} +#end#end"}";} #end }
mapper.java.vm
package ${package.Mapper};import ${package.Entity}.${entity}; import ${superMapperClassPackage};/*** @Description ${entity}Mapper 接口* @Author ${author}* @Date ${date}* @Version 1.0.1*/ #if(${kotlin}) interface ${table.mapperName} : ${superMapperClass}<${entity}> #else public interface ${table.mapperName} extends ${superMapperClass}<${entity}> {} #end
- 此时,已经可以运行Generator,实现domain和dao的生成
- 接下来实现创建时间和更新时间的自动填充(在config下创建MyMetaObjectHandler重写MetaObjectHandler中的insertFill和updateFill方法)
package com.companyName.db.config;import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler; import org.apache.ibatis.reflection.MetaObject; import org.springframework.stereotype.Component;import java.util.Date;/*** 自动填充处理类* @author* @version 1.0* @see**/ @Component public class MyMetaObjectHandler implements MetaObjectHandler {@Overridepublic void insertFill(MetaObject metaObject) {this.setFieldValByName("createTime", System.currentTimeMillis()/1000, metaObject);this.setFieldValByName("updateTime", System.currentTimeMillis()/1000, metaObject); // this.setFieldValByName("gmtModified", new Date(), metaObject); // this.setFieldValByName("creatorId", new Long(111), metaObject); // this.setFieldValByName("gmtCreat",new Date(), metaObject); // this.setFieldValByName("availableFlag",true, metaObject);}@Overridepublic void updateFill(MetaObject metaObject) {this.setFieldValByName("createTime", System.currentTimeMillis()/1000, metaObject);this.setFieldValByName("updateTime", System.currentTimeMillis()/1000, metaObject); // this.setFieldValByName("gmtModified", new Date(), metaObject);} }
配置完成!!!接下来使用MybatisPlus的insert和update方法时,创建时间和更新时间会自动写入!!!
关于MybatisPlus使用Generator自动生成代码的实现(包含创建时间和更新时间的自动填充)相关推荐
- javaweb项目:用户(登录和注销)实现 SSM框架(mybatis-generator自动生成代码)
SSM框架的搭建环境(Spring,SpringMVC,Mybatis) 使用工具:maven.idea.tomcat用的是8.jdk版本1.8 一.整个项目的结构: 用户模块流程 pom.xml - ...
- MyBatisPlus自动生成代码springboot+mybatis+mysql 以及动态sql生成方法(测试可用版)
用了一段时间的springboot,想着百度一下自动生成代码的方式,包括后面如何生成动态sql方法的方式. 摸索了几天,整理一下: ** 1 自动生成代码方式:com.baomidou.mybatis ...
- mybatis-Plus自动生成代码
1.pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="h ...
- SpringBoot如何自动生成实体类和Dao层以及映射文件(mybatis generator 自动生成代码)
一.首先添加自动生成代码插件 <!-- mybatis generator 自动生成代码插件 生成时解除注释 --><plugin><groupId>org.myb ...
- 使用Mybatis Generator自动生成代码
MyBatis Generator(MBG)是MyBatis MyBatis 和iBATIS的代码生成器. 它将为所有版本的MyBatis以及版本2.2.0之后的iBATIS版本生成代码. 它将内省数 ...
- Eclipse使用mybatis generator自动生成代码
一.写在前面 Mybatis属于半自动ORM,在使用这个框架中,工作量最大的就是书写Mapping的映射文件,由于手动书写很容易出错,我们可以利用Mybatis-Generator来帮我们自动生成文件 ...
- SpringBoot入门篇--整合mybatis+generator自动生成代码+druid连接池+PageHelper分页插件
我们这一一篇博客讲的是如何整合Springboot和Mybatis框架,然后使用generator自动生成mapper,pojo等文件.然后再使用阿里巴巴提供的开源连接池druid,这个连接池的好处我 ...
- 用mybatis的generator自动生成代码--坑我都走了一遍,后面的同学别踩了
先说什么是mybatis-generator? mybatis-geneator是一款mybatis自动代码生成工具,可以通过配置,快速生成mapper和xml文件. 步骤一:在pom文件中添加插件配 ...
- Mybatis自动生成代码插件generator
Mybatis自动生成代码插件generator 1.pom maven依赖 <dependencies><dependency><groupId>org.myba ...
最新文章
- 微信小程序动画无限循环 掉花
- UVA 315 :Network (无向图求割顶)
- 最佳实践系列:前端代码标准和最佳实践
- 关于清除浮动那些事儿~
- 获取最大轮廓 opencv
- wxWidgets:wxListCtrl类用法
- SpringBoot高级-任务-邮件任务
- idea 父文件_万事开头难!最新MyBatis程序配置教程(IDEA版)
- 网站链接自动化测试原理及工具介绍
- 小程序路由及路由传参
- deepin php docker,Deepin15.10安装Docker
- 一句Python,一句R︱数据的合并、分组、排序、翻转、集合
- php mysql 组件_Ubuntu20.04安装apache、mysql、php、phpmyadmin、wordpress(一)
- PCWorld:火狐浏览器已宣告死亡
- showModalDialog的title问题,去掉网页对话框
- AD生成BOM表/元器件表
- 数据库设计阶段和三个重要的设计模型
- 多表关联查询(Oracle)
- [转自CSDN]EXCEL工资数据表打印
- RacerX Effective, Static Detection of Race Conditions and Deadlocks调研笔记