本文记录自定义VM模板生成对象,使用自定义注解
一、所需部分依赖
主要展示mybatis-plus所需依赖,springboot基础依赖不在展示
……
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!--阿里数据库连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.69</version>
</dependency>
<!--mybatis-plus -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.1.0</version>
</dependency>
<!--myabtis-plus代码生成器-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.1.0</version>
</dependency>
<!--代码生成所需的velocity模板依赖-->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.2</version>
</dependency>
<!--代码生成所需的freemarker模板依赖-->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.30</version>
</dependency>
二、自定义依赖@FieldName
@Retention(RetentionPolicy.RUNTIME)
public @interface FieldName {
String value() default "";
}
三、mybatis-plus配置
/**
* mybatis-plus配置
*/
@MapperScan(basePackages = "com.example.mapper", sqlSessionFactoryRef = "sqlSessionFactory")
@Configuration
public class MybatisPlusConfig {
@Bean(name = "dataSource", destroyMethod = "close")
public RoutableDataSource getDataSource(@Value("${dbName}") String dbName) {
RoutableDataSource ds = new RoutableDataSource();
ds.setDbName(dbName);
ds.init();
ds.setConnectionProperties(new HashMap<String, String>() {{
put("serverTimezone", "GMT%2B8");
}});
return ds;
}
@Bean(name = "transactionManager")
public PlatformTransactionManager transactionManager(@Qualifier("dataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
@Bean("sqlSessionFactory")
public SqlSessionFactory userSqlSessionFactory(@Qualifier("dataSource") DataSource dataSource) throws Exception {
MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
bean.setMapperLocations(resolver.getResources("classpath:mapper/*.xml"));
bean.setDataSource(dataSource);
PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
paginationInterceptor.setDialectType("mysql");
bean.setPlugins(new Interceptor[]{paginationInterceptor});
return bean.getObject();
}
}
四、代码生成器
动手能力强的可以根据官网文档自行修改
public class MyCodeGenerator {
private static String NAME_SPACE = "com.example.pojo.compareObj";
//MYSQL链接、账号密码之类的
private static String MYSQL_URL = "数据库地址:端口";
private static String MYSQL_DATABASE = "数据库名";
private static String MYSQL_USERNAME = "账号";
private static String MYSQL_PASSWORD = "密码";
//项目的Module名,用于确定生成代码的路径,不是Module项目不用填
private static String MODULE_PROJ = "";
//设置模块名
private static String MODULE_NAME = "";
//设置作者
private static String AUTHOR = "";
/**
* 读取控制台内容
*/
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.isNotEmpty(ipt)) {
return ipt;
}
}
throw new MybatisPlusException("请输入正确的" + tip + "!");
}
public static void main(String[] args) {
// 代码生成器
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
gc.setOutputDir(projectPath + MODULE_PROJ + "/src/main/java");
gc.setAuthor(AUTHOR);
gc.setFileOverride(true); // 文件覆盖
gc.setEnableCache(false); //是否开启二级缓存
gc.setOpen(false);
gc.setDateType(DateType.TIME_PACK);
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setDbType(DbType.MYSQL);
dsc.setUrl(String.format("jdbc:mysql://%s/%s?useUnicode=true&serverTimezone=GMT&useSSL=false&characterEncoding=utf8", MYSQL_URL, MYSQL_DATABASE));
dsc.setDriverName("com.mysql.cj.jdbc.Driver"); //com.mysql.jdbc.Driver
dsc.setUsername(MYSQL_USERNAME);
dsc.setPassword(MYSQL_PASSWORD);
mpg.setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setModuleName(MODULE_NAME);
pc.setParent(NAME_SPACE);
//配置包的文件路径
//pc.setController("controller");
pc.setEntity("compareObj");
//pc.setEntity("entity");
//pc.setMapper("mapper");
//pc.setService("service");
//pc.setServiceImpl("service.impl");
mpg.setPackageInfo(pc);
// 自定义配置
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
// to do nothing
}
};
// 如果模板引擎是 freemarker
// String templatePath = "/templates/mapper.xml.ftl";
// 如果模板引擎是 velocity
String templatePath = "/templates/vm/entity.java.vm";
List<FileOutConfig> focList = new ArrayList<>();
focList.add(new FileOutConfig(templatePath) {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输入文件名称
return projectPath + MODULE_PROJ + "/src/main/java/com/example/pojo/compareObj"
+ "/" + tableInfo.getEntityName() + StringPool.DOT_JAVA;
}
});
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
// 配置模板
TemplateConfig templateConfig = new TemplateConfig();
//设置为null就不会自动生成对应模块了
templateConfig.setXml(null);
templateConfig.setEntity(null);
templateConfig.setController(null);
templateConfig.setService(null);
templateConfig.setServiceImpl(null);
templateConfig.setMapper(null);
mpg.setTemplate(templateConfig);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
// 设置命名规则
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setEntityLombokModel(true);
// 写于父类中的公共字段
//strategy.setSuperEntityColumns("id");
//设置controller的父类,没有就不要配置
//strategy.setSuperControllerClass("com.suzhou.springdemo.controller");
strategy.setControllerMappingHyphenStyle(true);
strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
strategy.setTablePrefix(pc.getModuleName() + "_");
mpg.setStrategy(strategy);
// 选择 freemarker 引擎需要指定如下加,注意 pom 依赖必须有!
//mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute();
}
}
五、自定义VM模板 entity.java.vm
package ${package.Entity};
#foreach($pkg in ${table.importPackages})
import ${pkg};
#end
import com.tehy.nip.be.walkingapi.config.FieldName;
import lombok.Data;
###set($str=${entity})
###set($end=$str.length() - 1)
###set($str=$str.substring(2,$end))
/**
*
* @author ${author}
* @date ${date}
*/
#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
public class ${entity} implements Serializable{
private static final long serialVersionUID=1L;
## ---------- BEGIN 字段循环遍历 ----------
#foreach($field in ${table.fields})
#if("$!field.comment" != "")
/**
* ${field.comment}
*/
@FieldName("${field.comment}")
#end
@TableId("${field.name}")
private ${field.propertyType} ${field.propertyName};
#end
}
六、生成实体类展示
/**
*
* @author xxx
* @date 2021-04-23
*/
@Data
@TableName("TeamMember")
public class TeamMember implements Serializable{
private static final long serialVersionUID=1L;
/**
* 主键
*/
@FieldName("主键")
@TableField("Id")
private Long Id;
/**
* 活动标识
*/
@FieldName("活动标识")
@TableField("ActivityId")
private Long ActivityId;
/**
* 队伍标识
*/
@FieldName("队伍标识")
@TableField("TeamId")
private Long TeamId;
/**
* 成员标识
*/
@FieldName("成员标识")
@TableField("MemberId")
private Long MemberId;
}