springboot集成mybatis-plus,完整文件
依赖${mybatisplus.version} 3.3.1 版本
com.baomidou
mybatis-plus-boot-starter
${mybatisplus.version}
com.baomidou
mybatis-plus
${mybatisplus.version}
com.baomidou
mybatis-plus-generator
${mybatisplus.version}
生成器:
package com.easysign;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import java.util.*;
public class MybatisPlusRunGenerator {
/**
* 包名 自定义的包名
*/
public static String packageCustom = "com.easysign"; //包名
public static String OutputDir = "D:\\cloud-api\\src\\main\\java"; //文件路径
public static String author = "free.li";
public static String dataBaseUrl = "jdbc:mysql://192.168.1.237:3306/uumszs1?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC";
public static String outXmlPath = "D:\\cloud-api\\src\\main\\resources\\mappers\\";
public static void main(String[] args) {
String tablePre = "tbl_"; //表前缀
//添加表名
List tables = new ArrayList<>(10);
tables.add("SYNC_PERSONALUSERINFO");
//tables.add("tbl_esand_proof");
// 代码生成器
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
// String projectPath = System.getProperty("user.dir");
gc.setOutputDir(OutputDir);
gc.setAuthor(author);
gc.setOpen(false);
//开启 BaseResultMap
gc.setBaseResultMap(true);
gc.setBaseColumnList(true);
gc.setEnableCache(true);
// 实体属性 Swagger2 注解
gc.setSwagger2(true);
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl(dataBaseUrl);
// dsc.setSchemaName("public");
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("root");
dsc.setTypeConvert(new MySqlTypeConvert() {
@Override
public DbColumnType processTypeConvert(GlobalConfig globalConfig, String fieldType) {
System.out.println("转换类型:" + fieldType);
//tinyint转换成Boolean
if ( fieldType.toLowerCase().contains( "longblob" )||fieldType.toLowerCase().contains( "blob" ) ) {
return DbColumnType.BYTE_ARRAY;
}
if ( fieldType.toLowerCase().contains( "decimal" )) {
return DbColumnType.INTEGER;
}
//将数据库中datetime转换成date
if ( fieldType.toLowerCase().contains( "datetime" ) ) {
return DbColumnType.DATE;
}
return (DbColumnType) super.processTypeConvert(globalConfig, fieldType);
}
});
mpg.setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
// 不需要 直接注释掉
// pc.setModuleName(scanner("模块名"));
//设置包名
pc.setParent(packageCustom);
mpg.setPackageInfo(pc);
// 自定义配置
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
// to do nothing
}
};
// 自定义输出配置
List focList = new ArrayList<>();
// 自定义配置会被优先输出
focList.add(new FileOutConfig("/templates/mapper.xml.vm") {
@Override
public String outputFile(TableInfo tableInfo) {
return outXmlPath + tableInfo.getEntityName() + ".xml";
}
});
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
// 配置模板
TemplateConfig tc = new TemplateConfig();
//控制 不生成 controller
// tc.setController("");
tc.setEntity("/templates/entity.java.vm");
tc.setService("/templates/service.java.vm");
tc.setServiceImpl("/templates/serviceImpl.java.vm");
//tc.setController("/templates/controller.java.vm");
tc.setController(""); //不生成controller
tc.setMapper("/templates/mapper.java.vm");
// // 如上任何一个模块如果设置 空 OR Null 将不生成该模块。
tc.setXml(null);
mpg.setTemplate(tc);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
//自定义继承的Entity类全称,带包名 舍弃 不需要
// strategy.setSuperEntityClass("com.baomidou.ant.common.BaseEntity");
strategy.setEntityLombokModel(true);
//不需要 controller 舍弃
strategy.setRestControllerStyle(true);
// 公共父类
// strategy.setSuperControllerClass("com.baomidou.ant.common.BaseController");
// 写于父类中的公共字段
//strategy.setSuperEntityColumns("id");
//strategy.setSuperEntityColumns(new String[] { "id","create_date","create_by","update_date","update_by","remarks","del_flag" });
//要添加的表
strategy.setInclude(tables.toArray(new String[]{}));
strategy.setControllerMappingHyphenStyle(true);
//表名前缀 这样生成的bean里面 就没有前缀了
strategy.setTablePrefix(tablePre);
mpg.setStrategy(strategy);
mpg.execute();
}
}
application.yml配置:
mybatis-plus:
mapper-locations: classpath:mappers/*.xml
#实体扫描,多个package用逗号或者分号隔离
typeAliasesPackage: com.easysign.entity
global-config:
db-config:
#主键类型 0:"数据库ID自增", 1:"用户输入ID",2:"全局唯一ID (数字类型唯一ID)", 3:"全局唯一ID UUID"; 4,UUID
id-type: 4
#字段策略 0:"忽略判断",1:"非 NULL 判断"),2:"非空判断"
field-strategy: 1
#数据库大写下划线转换
capital-mode: true
configuration:
map-underscore-to-camel-case: true
cache-enabled: false
#配置JdbcTypeForNull
jdbc-type-for-null: 'null'
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
# 驼峰下划线转换
lazy-loading-enabled: true
# 开启的话,延时加载一个属性时会加载该对象全部属性,否则按需加载属性
multiple-result-sets-enabled: true
use-generated-keys: true
default-statement-timeout: 60
default-fetch-size: 100
自定义生成的模板:
entity
package ${package.Entity};
#foreach($pkg in ${table.importPackages})
import ${pkg};
#end
#if(${entityLombokModel})
import lombok.Data;
import lombok.experimental.Accessors;
#end
#set($tablecomment = "")
#set($tabletype = "")
#foreach($e in $table.comment.split(","))
#if( $foreach.count == 1 )
#set($tablecomment = $e)
#elseif( $foreach.count == 2 )
#set($tabletype = $e)
#end
#end
/**
*
* $!{tablecomment}
*
*
* @author ${author}
* @since ${date}
*/
#if(${entityLombokModel})
@Data
@Accessors(chain = true)
#end
#if(${table.convert})
@TableName("${table.name}")
#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
private static final long serialVersionUID = 1L;
## ---------- BEGIN 字段循环遍历 ----------
#foreach($field in ${table.fields})
#set($comment = "")
#set($type = "")
#set($isNullAble = true)
#set($defaultValue = false)
#set($listIsShow = true)
#set($listIsSearch = false)
#foreach( $e in $field.comment.split(","))
#if( $foreach.count == 1 )
#set($comment = $e)
#elseif( $foreach.count == 2 )
#set($type = $e)
#elseif( $foreach.count == 3)
#if($e == "YES")
#set($isNullAble = true)
#else
#set($isNullAble = false)
#end
#elseif( $foreach.count == 4)
#if($e == "true")
#set($defaultValue = true)
#else
#set($defaultValue = false)
#end
#elseif( $foreach.count == 5)
#if($e == "true")
#set($listIsShow = true)
#else
#set($listIsShow = false)
#end
#elseif( $foreach.count == 6)
#if($e == "true")
#set($listIsSearch = true)
#else
#set($listIsSearch = false)
#end
#end
#end
#if(${field.keyFlag})
#set($keyPropertyName=${field.propertyName})
#end
#if("$!comment" != "")
/**
* ${comment}
*/
#end
#if(${field.keyFlag})
## 主键
#if(${field.keyIdentityFlag})
@TableId(value="${field.name}", type= IdType.AUTO)
#elseif(${field.convert})
@TableId("${field.name}")
#end
## 普通字段
#elseif(${field.fill})
## ----- 存在字段填充设置 -----
#if(${field.convert})
@TableField(value = "${field.name}", fill = FieldFill.${field.fill})
#else
@TableField(fill = FieldFill.${field.fill})
#end
#elseif(${field.convert})
@TableField("${field.name}")
#end
## 乐观锁注解
#if(${versionFieldName}==${field.name})
@Version
#end
## 逻辑删除注解
#if(${logicDeleteFieldName}==${field.name})
@TableLogic
#end
private ${field.propertyType} ${field.propertyName};
#end
## ---------- END 字段循环遍历 ----------
#if(!${entityLombokModel})
#foreach($field in ${table.fields})
#set($getprefix="get")
#set($setprefix="set")
public ${field.propertyType} ${getprefix}${field.capitalName}() {
return ${field.propertyName};
}
#if(${entityBuilderModel})
public ${entity} ${setprefix}${field.capitalName}(${field.propertyType} ${field.propertyName}) {
#else
public void ${setprefix}${field.capitalName}(${field.propertyType} ${field.propertyName}) {
#end
this.${field.propertyName} = ${field.propertyName};
#if(${entityBuilderModel})
return this;
#end
}
#end
#end
#if(${entityColumnConstant})
#foreach($field in ${table.fields})
public static final String ${field.name.toUpperCase()} = "${field.name}";
#end
#end
#if(!${entityLombokModel})
@Override
public String toString() {
return "${entity}{" +
#foreach($field in ${table.fields})
#if($!{velocityCount}==1)
"${field.propertyName}=" + ${field.propertyName} +
#else
", ${field.propertyName}=" + ${field.propertyName} +
#end
#end
"}";
}
#end
}
serviceImpl:
#set($tablecomment = "")
#set($tabletype = "")
#foreach($e in $table.comment.split(","))
#if( $foreach.count == 1 )
#set($tablecomment = $e)
#elseif( $foreach.count == 2 )
#set($tabletype = $e)
#end
#end
package ${package.ServiceImpl};
import ${package.Entity}.${entity};
import ${package.Mapper}.${table.mapperName};
import ${package.Service}.${table.serviceName};
import ${superServiceImplClassPackage};
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
/**
*
* $!{tablecomment} 服务实现类
*
*
* @author ${author}
* @since ${date}
*/
@Service
@Slf4j
#if(${kotlin})
open class ${table.serviceImplName} : ${superServiceImplClass}<${table.mapperName}, ${entity}>(), ${table.serviceName} {
}
#else
public class ${table.serviceImplName} extends ${superServiceImplClass}<${table.mapperName}, ${entity}> implements ${table.serviceName} {
}
#end
mapper
#set($tablecomment = "")
#set($tabletype = "")
#foreach($e in $table.comment.split(","))
#if( $foreach.count == 1 )
#set($tablecomment = $e)
#elseif( $foreach.count == 2 )
#set($tabletype = $e)
#end
#end
package ${package.Mapper};
import ${package.Entity}.${entity};
import ${superMapperClassPackage};
/**
*
* $!{tablecomment} Mapper 接口
*
*
* @author ${author}
* @since ${date}
*/
#if(${kotlin})
interface ${table.mapperName} : ${superMapperClass}<${entity}>
#else
public interface ${table.mapperName} extends ${superMapperClass}<${entity}> {
}
#end
mapper.xml
#if(${baseResultMap})
#foreach($field in ${table.fields})
#if(${field.keyFlag})##生成主键排在第一位
#end
#end
#foreach($field in ${table.commonFields})##生成公共字段
#end
#foreach($field in ${table.fields})
#if(!${field.keyFlag})##生成普通字段
#end
#end
#end
#if(${baseColumnList})
#foreach($field in ${table.commonFields})
#if(${field.name} == ${field.propertyName})${field.name}#else${field.name} AS ${field.propertyName}#end,
#end
${table.fieldNames}
#end
service接口:
package ${package.Service};
import ${package.Entity}.${entity};
import ${superServiceClassPackage};
#set($tablecomment = "")
#set($tabletype = "")
#foreach($e in $table.comment.split(","))
#if( $foreach.count == 1 )
#set($tablecomment = $e)
#elseif( $foreach.count == 2 )
#set($tabletype = $e)
#end
#end
/**
*
* $!{tablecomment} 服务类
*
*
* @author ${author}
* @since ${date}
*/
#if(${kotlin})
interface ${table.serviceName} : ${superServiceClass}<${entity}>
#else
public interface ${table.serviceName} extends ${superServiceClass}<${entity}> {
}
#end