这里实现的方案是
MySQL的读取数据库信息,表信息,生成dao,service,model,web,xml
freemarker配置模板,Template输出读取到的对象数据,获取模板输出流,在指定的包位置生成.java文件。
注意:这里不负责生成前端代码,只生成后端的代码以及restful风格的网络接口(当然,你也能自己修改)
1.先配置数据库读取信息
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="map.AutoGen_SqlMap">
<resultMap id="TableProfileDOMap" type="TableProfileDOAlias">
<result column="TABLE_SCHEMA" property="table_schema" />
<result column="TABLE_NAME" property="table_name" />
<result column="TABLE_COMMENT" property="table_comment" />
</resultMap>
<resultMap id="TableColumnsDOMap" type="TableColumnsDOAlias">
<result column="TABLE_SCHEMA" property="table_schema" />
<result column="TABLE_NAME" property="table_name" />
<result column="COLUMN_NAME" property="column_name" />
<result column="ORDINAL_POSITION" property="ordinal_position" />
<result column="IS_NULLABLE" property="is_nullable" />
<result column="DATA_TYPE" property="data_type" />
<result column="CHARACTER_MAXIMUM_LENGTH" property="character_maximum_length" />
<result column="COLUMN_TYPE" property="column_type" />
<result column="COLUMN_KEY" property="column_key" />
<result column="COLUMN_COMMENT" property="column_comment" />
</resultMap>
<select id="table_profile_find" resultMap="TableProfileDOMap" parameterType="java.util.Map">
SELECT * FROM information_schema.TABLES WHERE TABLE_NAME = #{tableName} AND TABLE_SCHEMA=#{dbName};
</select>
<select id="table_columns_list" resultMap="TableColumnsDOMap" parameterType="java.util.Map">
SELECT * FROM information_schema.COLUMNS WHERE TABLE_NAME=#{tableName} AND TABLE_SCHEMA=#{dbName}
ORDER BY
ORDINAL_POSITION
</select>
</mapper>
上面的两断SQL分别读取数据库信息,表信息。
这里省略DB的相关配置。有需要的同学下拉最后
2.freemarker配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:task="http://www.springframework.org/schema/task" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd"
default-autowire="byName">
<context:annotation-config />
<!-- freemarker配置 -->
<bean id="freemarkerConfig"
class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<property name="templateLoaderPath" value="classpath:template/" />
<property name="freemarkerSettings">
<props>
<prop key="template_update_delay">0</prop>
<prop key="default_encoding">UTF-8</prop>
<prop key="number_format">0.##########</prop>
<prop key="datetime_format">yyyy-MM-dd HH:mm:ss</prop>
<prop key="classic_compatible">true</prop>
<prop key="template_exception_handler">ignore</prop>
</props>
</property>
<property name="freemarkerVariables">
<map>
<entry key="imageUri" value="${imageUri}"></entry>
<entry key="cssUri" value="${cssUri}"></entry>
<entry key="jsUri" value="${jsUri}"></entry>
</map>
</property>
</bean>
</beans>
3.接下来配置对应的刀/服务/网络等输出模板
这里举例生产daoimpl
package ${hibernate.classPackage};
import ${dao.importName};
import com.winhc.mis.pojo.${model.className};
import com.winhc.mis.pojo.${model.className}Example;
import org.apache.commons.lang.StringUtils;
import com.winhc.mis.PageJdbcTemplate.PageBean;
import com.winhc.mis.PageJdbcTemplate.PageQueryHelper;
import com.winhc.mis.mapper.${model.className}Mapper;
import org.springframework.stereotype.Service;
import java.util.List;
import javax.annotation.Resource;
import ${qo.importName};
/**
* <${hibernate.describe}>
* <功能详细描述>
*
* @auth:DONNIE
*/
@Service
public class ${hibernate.className} implements ${dao.className} {
@Resource
private ${model.className}Mapper ${model.classNameAttr}Mapper;
@Resource
private PageQueryHelper pageQueryHelper;
@Override
public ${model.className} save(${model.className} obj) {
// TODO Auto-generated method stub
${model.classNameAttr}Mapper.insertSelective(obj);
return obj;
}
@Override
public ${model.className} update(${model.className} obj) {
// TODO Auto-generated method stub
${model.classNameAttr}Mapper.updateByPrimaryKeySelective(obj);
return obj;
}
@Override
public void delete(String ${model.primaryKey.attrName}) {
// TODO Auto-generated method stub
if(StringUtils.isEmpty(${model.primaryKey.attrName})){
return ;
}
<#if 'Integer' == '${model.primaryKey.javaTypeName}' >
${model.classNameAttr}Mapper.deleteByPrimaryKey(Integer.parseInt(${model.primaryKey.attrName}));
<#elseif 'Long' == '${model.primaryKey.javaTypeName}'>
${model.classNameAttr}Mapper.deleteByPrimaryKey(Long.parseLong(${model.primaryKey.attrName}));
<#elseif 'String' == '${model.primaryKey.javaTypeName}'>
${model.classNameAttr}Mapper.deleteByPrimaryKey(${model.primaryKey.attrName});
</#if>
}
@Override
public List<${model.className}> query(${qo.className} obj) {
// TODO Auto-generated method stub
${model.className}Example example=new ${model.className}Example();
${model.className}Example.Criteria criteria=example.createCriteria();
<#list model.columnsList as column>
<#if column.javaTypeName == 'String'>
if(StringUtils.isNotBlank(obj.get${column.domainName}())){
criteria.and${column.domainName}EqualTo(obj.get${column.domainName}());
}
<#else>
if(obj.get${column.domainName}() != null ){
criteria.and${column.domainName}EqualTo(obj.get${column.domainName}());
}
</#if>
</#list>
example.setOrderByClause(" ${model.primaryKey.column_name} desc ");
List<${model.className}> list =${model.classNameAttr}Mapper.selectByExample(example);
return list;
}
@Override
public ${model.className} query(String ${model.primaryKey.attrName}) {
// TODO Auto-generated method stub
if(StringUtils.isEmpty(${model.primaryKey.attrName})){
return null;
}
<#if 'Integer' == '${model.primaryKey.javaTypeName}' >
return ${model.classNameAttr}Mapper.selectByPrimaryKey(Integer.parseInt(${model.primaryKey.attrName}));
<#elseif 'Long' == '${model.primaryKey.javaTypeName}'>
return ${model.classNameAttr}Mapper.selectByPrimaryKey(Long.parseLong(${model.primaryKey.attrName}));
<#elseif 'String' == '${model.primaryKey.javaTypeName}'>
return ${model.classNameAttr}Mapper.selectByPrimaryKey(${model.primaryKey.attrName});
</#if>
}
@Override
public PageBean<${model.className}> queryAll(${qo.className} dto) {
// TODO Auto-generated method stub
StringBuffer sb = new StringBuffer("select * from ${model.primaryKey.table_name} as ${model.classNameAttr} where 1=1 ");
StringBuffer conditionSB = new StringBuffer();
String startDate = dto.getStartDate();
String endDate = dto.getEndDate();
<#list model.columnsList as column>
<#if '${column.javaTypeName}' == 'String'>
String ${column.attrName} = dto.get${column.domainName}();
if(StringUtils.isNotEmpty(${column.attrName})) {
conditionSB.append(" and ${model.classNameAttr}.${column.column_name} =");
conditionSB.append("'");
conditionSB.append(${column.attrName});
conditionSB.append("'");
}
<#elseif '${column.javaTypeName}' == 'Integer'>
Integer ${column.attrName} = dto.get${column.domainName}();
if(${column.attrName} != null) {
conditionSB.append(" and ${model.classNameAttr}.${column.column_name} =");
conditionSB.append(${column.attrName});
}
<#elseif '${column.javaTypeName}' == 'Long'>
Long ${column.attrName} = dto.get${column.domainName}();
if(${column.attrName} != null) {
conditionSB.append(" and ${model.classNameAttr}.${column.column_name} =");
conditionSB.append(${column.attrName});
}
<#elseif '${column.javaTypeName}' == 'Date'>
if(StringUtils.isNotEmpty(startDate)) {
conditionSB.append(" and ${model.classNameAttr}.${column.column_name} >=");
conditionSB.append("'");
conditionSB.append(startDate.replaceAll("-", "").trim());
conditionSB.append("'");
}
if(StringUtils.isNotEmpty(endDate)) {
conditionSB.append(" and ${model.classNameAttr}.${model.column_name} <=");
conditionSB.append("'");
conditionSB.append(endDate.replaceAll("-", "").trim());
conditionSB.append("'");
}
</#if>
</#list>
conditionSB.append(" order by ${model.classNameAttr}.${model.primaryKey.column_name} desc ");
String sql = sb.append(conditionSB).toString();
PageBean<${model.className}> list = pageQueryHelper.query(sql, dto.getPageSize(),
dto.getPageNum(), ${model.className}.class);
return list;
}
}
上面是举例如何编写后缀为.ftl的模板文件,可以根据自己的需要编写不同的模板
4.daoimpl对应的配置信息
package com.srcgen.config;
import com.srcgen.builder.ParentConfig;
import org.apache.commons.lang3.StringUtils;
/**
* <一句话功能简述>
* <功能详细描述>
*
* @auth:DONNIE
* @see: [相关类/方法](可选)
* @since [产品/模块版本] (可选)
*/
public class DaoImplConfig extends ParentConfig {
//包所在位置
private String DefaultClassPackage = "${packageName}.service.${autoModel}.dao";
//保存路径
private String DefaultSaveDir = "${saveDir}/service/${autoModel}/dao/";
//模板所在位置
private String DefaultTemplateDir = "daoImpl.ftl";
@Override
public String getClassPackage() {
return StringUtils.defaultIfEmpty(classPackage, DefaultClassPackage);
}
@Override
public String getSaveDir() {
return StringUtils.defaultIfEmpty(saveDir,DefaultSaveDir);
}
@Override
public String getTemplateDir() {
return StringUtils.defaultIfEmpty(templateDir,DefaultTemplateDir);
}
}
需要继承ParentConfig
package com.srcgen.builder;
import java.io.Serializable;
public abstract class ParentConfig implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* 包名
*/
protected String classPackage;
/**
* 文件存储路径
*/
protected String saveDir;
/**
* 模板所在位置
*/
protected String templateDir;
/**
* 描述
*/
private String describe;
/**
* 方法名称
*/
private String methodDomain;
/**
* 类名称,首字母大写的驼峰==domain
*/
protected String className;
public String getDescribe() {
return describe;
}
public void setDescribe(String describe) {
this.describe = describe;
}
public String getMethodDomain() {
return methodDomain;
}
public void setMethodDomain(String methodDomain) {
this.methodDomain = methodDomain;
}
public abstract String getClassPackage();
public void setClassPackage(String classPackage) {
this.classPackage = classPackage;
}
public abstract String getSaveDir();
public void setSaveDir(String saveDir) {
this.saveDir = saveDir;
}
public abstract String getTemplateDir() ;
public void setTemplateDir(String templateDir) {
this.templateDir = templateDir;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
/**
* 类引用名称,驼峰=attr
*/
public String getClassNameAttr() {
return className.substring(0,1).toLowerCase()+className.substring(1);
}
/**
* 导入包名称
*/
public String getImportName() {
return classPackage+"."+className;
}
}
最后是模板生成者
package com.srcgen.builder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import com.alibaba.fastjson.JSON;
import com.srcgen.config.ApiConfig;
import com.srcgen.config.ControllerConfig;
import com.srcgen.config.ConvertorConfig;
import com.srcgen.config.DAOConfig;
import com.srcgen.config.DTOConfig;
import com.srcgen.config.DaoImplConfig;
import com.srcgen.config.ModelConfig;
import com.srcgen.config.Mysql2JavaType;
import com.srcgen.config.ServiceImplConfig;
import com.srcgen.config.VoConfig;
import com.srcgen.domain.TableColumnsDO;
import com.srcgen.domain.entity.TableEntity;
import com.srcgen.utils.CamelCaseUtils;
/**
* <一句话功能简述>
* <功能详细描述>
*
* @auth:DONNIE
* @see: [相关类/方法](可选)
* @since [产品/模块版本] (可选)
*/
public class TemplateMapBuilder {
public TemplateMapBuilder(){
}
public Map<String,ParentConfig> build(){
return build(this);
}
public static Map<String,ParentConfig> build(TemplateMapBuilder builder){
formatColumns(builder);
Map<String,ParentConfig> map = new HashMap();
String domain = CamelCaseUtils.toCapitalize(builder.tableName);
if(builder.apiEnabled){
ApiConfig apiConfig = new ApiConfig();
apiConfig.setClassName(domain+API_SUFFIX);//CaseBaseInfoDao
if(StringUtils.isNoneEmpty(builder.apiPackage)){
apiConfig.setClassPackage(builder.apiPackage);
}
if(StringUtils.isNoneEmpty(builder.apiSaveDir)){
apiConfig.setSaveDir(builder.apiSaveDir);
}
if(StringUtils.isNoneEmpty(builder.apiTemplate)){
apiConfig.setTemplateDir(builder.apiTemplate);
}
map.put("api",apiConfig);
}
if(builder.dtoEnabled){
DTOConfig dtoConfig = new DTOConfig();
if(StringUtils.isNoneEmpty(builder.dtoPackage)){
dtoConfig.setClassPackage(builder.dtoPackage);
}
if(StringUtils.isNoneEmpty(builder.dtoSaveDir)){
dtoConfig.setSaveDir(builder.dtoSaveDir);
}
if(StringUtils.isNoneEmpty(builder.dtoTemplate)){
dtoConfig.setTemplateDir(builder.dtoTemplate);
}
dtoConfig.setClassName(domain+DTO_SUFFIX);
map.put("qo",dtoConfig);
}
if(builder.voEnabled){
VoConfig voConfig = new VoConfig();
if(StringUtils.isNoneEmpty(builder.voPackage)){
voConfig.setClassPackage(builder.voPackage);
}
if(StringUtils.isNoneEmpty(builder.voSaveDir)){
voConfig.setSaveDir(builder.voSaveDir);
}
if(StringUtils.isNoneEmpty(builder.voTemplate)){
voConfig.setTemplateDir(builder.voTemplate);
}
voConfig.setQueryParams(builder.columnList);
voConfig.setClassName(domain+VO_SUFFIX);
map.put("vo",voConfig);
}
if(builder.daoEnabled){
DAOConfig daoConfig = new DAOConfig();
if(StringUtils.isNoneEmpty(builder.daoPackage)){
daoConfig.setClassPackage(builder.daoPackage);
}
if(StringUtils.isNoneEmpty(builder.daoSaveDir)){
daoConfig.setSaveDir(builder.daoSaveDir);
}
if(StringUtils.isNoneEmpty(builder.daoTemplate)){
daoConfig.setTemplateDir(builder.daoTemplate);
}
daoConfig.setClassName(domain+DAO_SUFFIX);
map.put("dao",daoConfig);
}
if(builder.hibernateEnabled){
DaoImplConfig hibernateConfig = new DaoImplConfig();
if(StringUtils.isNoneEmpty(builder.hibernatePackage)){
hibernateConfig.setClassPackage(builder.hibernatePackage);
}
if(StringUtils.isNoneEmpty(builder.hibernateSaveDir)){
hibernateConfig.setSaveDir(builder.hibernateSaveDir);
}
if(StringUtils.isNoneEmpty(builder.hibernateTemplate)){
hibernateConfig.setTemplateDir(builder.hibernateTemplate);
}
hibernateConfig.setClassName(domain+DAOIMPL_SUFFIX);
map.put("hibernate",hibernateConfig);
}
if(builder.modelEnabled){
ModelConfig modelConfig = new ModelConfig();
if(StringUtils.isNoneEmpty(builder.modelPackage)){
modelConfig.setClassPackage(builder.modelPackage);
}
if(StringUtils.isNoneEmpty(builder.modelSaveDir)){
modelConfig.setSaveDir(builder.modelSaveDir);
}
if(StringUtils.isNoneEmpty(builder.modelTemplate)){
modelConfig.setTemplateDir(builder.modelTemplate);
}
modelConfig.setPrimaryKey(builder.primarykey);
modelConfig.setColumnsList(builder.columnList);
System.out.println(JSON.toJSONString(modelConfig.getColumnsList()));
modelConfig.setClassName(domain+MODEL_SUFFIX);
map.put("model",modelConfig);
}
if(builder.serviceImplEnabled){
ServiceImplConfig serviceImplConfig = new ServiceImplConfig();
if(StringUtils.isNoneEmpty(builder.serviceImplPackage)){
serviceImplConfig.setClassPackage(builder.serviceImplPackage);
}
if(StringUtils.isNoneEmpty(builder.serviceImplSaveDir)){
serviceImplConfig.setSaveDir(builder.serviceImplSaveDir);
}
if(StringUtils.isNoneEmpty(builder.serviceImplTemplate)){
serviceImplConfig.setTemplateDir(builder.serviceImplTemplate);
}
serviceImplConfig.setPrimaryKey(builder.primarykey.getAttrName());
serviceImplConfig.setClassName(domain+SERVICEIMPL_SUFFIX);
map.put("service",serviceImplConfig);
}
if(builder.controllerEnabled){
ControllerConfig controllerConfig = new ControllerConfig();
if(StringUtils.isNoneEmpty(builder.controllerPackage)){
controllerConfig.setClassPackage(builder.controllerPackage);
}
if(StringUtils.isNoneEmpty(builder.controllerSaveDir)){
controllerConfig.setSaveDir(builder.controllerSaveDir);
}
if(StringUtils.isNoneEmpty(builder.controllerTemplate)){
controllerConfig.setTemplateDir(builder.controllerTemplate);
}
controllerConfig.setClassName(domain+CONTROLLER_SUFFIX);
map.put("controller",controllerConfig);
}
if(builder.convertorEnabled){
ConvertorConfig convertorConfig = new ConvertorConfig();
if(StringUtils.isNoneEmpty(builder.convertorPackage)){
convertorConfig.setClassPackage(builder.convertorPackage);
}
if(StringUtils.isNoneEmpty(builder.convertorSaveDir)){
convertorConfig.setSaveDir(builder.convertorSaveDir);
}
if(StringUtils.isNoneEmpty(builder.convertorTemplate)){
convertorConfig.setTemplateDir(builder.convertorTemplate);
}
convertorConfig.setClassName(domain+CONVERTOR_SUFFIX);
map.put("convertor",convertorConfig);
}
//替换项目名和包名
//String projectPrefix = builder.projectName.split("-")[1];
for(String key:map.keySet()){
ParentConfig config = map.get(key);
config.setClassPackage(config.getClassPackage()
.replace("${packageName}", builder.sysPackageName)
.replace("${autoModel}", builder.sysAutoModel));
config.setSaveDir(builder.projectRoot+"/"+builder.projectName+"/"+ config.getSaveDir()
.replace("${saveDir}", builder.sysSaveDir)
.replace("${autoModel}", builder.sysAutoModel)
.replace("${projectName}",builder.projectName));
config.setDescribe(builder.tableInfo.getTable_comment());
config.setMethodDomain(domain);
}
return map;
}
/**
* 格式化表字段
* @param builder
*/
private static void formatColumns(TemplateMapBuilder builder) {
List<TableColumnsDO> columnsDOList = builder.columnList;
if(CollectionUtils.isEmpty(columnsDOList)){
throw new RuntimeException("表字段为空!");
}
for(TableColumnsDO columnsDO:columnsDOList){
columnsDO.setJavaTypeName(Mysql2JavaType.getJavaTypeFromMysql(columnsDO.getData_type()));
columnsDO.setAttrName( CamelCaseUtils.toCamelCase(columnsDO.getColumn_name()));//字段是驼峰
columnsDO.setDomainName(CamelCaseUtils.toCapitalize(columnsDO.getColumn_name()));//首字母大写
// columnsDO.setColumn_comment(StringEncoderUtils.gb2312ToUtf8(columnsDO.getColumn_comment()));
if("PRI".equals(columnsDO.getColumn_key())){
builder.primarykey = columnsDO;
}
}
}
private TableColumnsDO primarykey;
private static final String API_SUFFIX="Service";
private static final String DTO_SUFFIX="DTO";
private static final String VO_SUFFIX="VO";
private static final String DAO_SUFFIX="Dao";
private static final String DAOIMPL_SUFFIX="DaoImpl";
private static final String MODEL_SUFFIX="";
private static final String SERVICEIMPL_SUFFIX="ServiceImpl";
private static final String CONTROLLER_SUFFIX="Controller";
private static final String CONVERTOR_SUFFIX="Convertor";
/**
* 项目目录路径
*/
private String projectRoot;
/**
* 表名
*/
private String tableName;
/**
* 项目名称
*/
private String projectName;
/**
* 表
*/
private TableEntity tableInfo;
/**
* 表字段明细
*/
private List<TableColumnsDO> columnList;
private String sysPackageName;
private String sysSaveDir;
private String sysAutoModel;
private boolean convertorEnabled = true;
private String convertorPackage;
private String convertorSaveDir;
private String convertorTemplate;
private boolean controllerEnabled = true;
private String controllerPackage;
private String controllerSaveDir;
private String controllerTemplate;
private boolean apiEnabled = true;
private String apiPackage;
private String apiSaveDir;
private String apiTemplate;
private boolean dtoEnabled = true;
private String dtoPackage;
private String dtoSaveDir;
private String dtoTemplate;
private boolean voEnabled = true;
private String voPackage;
private String voSaveDir;
private String voTemplate;
private boolean daoEnabled = true;
private String daoPackage;
private String daoSaveDir;
private String daoTemplate;
private boolean hibernateEnabled = true;
private String hibernatePackage;
private String hibernateSaveDir;
private String hibernateTemplate;
private boolean modelEnabled = true;
private String modelPackage;
private String modelSaveDir;
private String modelTemplate;
private boolean serviceImplEnabled = true;
private String serviceImplPackage;
private String serviceImplSaveDir;
private String serviceImplTemplate;
public TemplateMapBuilder setConvertorEnabled(boolean convertorEnabled) {
this.convertorEnabled = convertorEnabled;
return this;
}
public TemplateMapBuilder setConvertorPackage(String convertorPackage) {
this.convertorPackage = convertorPackage;
return this;
}
public TemplateMapBuilder setConvertorSaveDir(String convertorSaveDir) {
this.convertorSaveDir = convertorSaveDir;
return this;
}
public TemplateMapBuilder setConvertorTemplate(String convertorTemplate) {
this.convertorTemplate = convertorTemplate;
return this;
}
public TemplateMapBuilder setControllerEnabled(boolean controllerEnabled) {
this.controllerEnabled = controllerEnabled;
return this;
}
public TemplateMapBuilder setControllerPackage(String controllerPackage) {
this.controllerPackage = controllerPackage;
return this;
}
public TemplateMapBuilder setControllerSaveDir(String controllerSaveDir) {
this.controllerSaveDir = controllerSaveDir;
return this;
}
public TemplateMapBuilder setControllerTemplate(String controllerTemplate) {
this.controllerTemplate = controllerTemplate;
return this;
}
public TemplateMapBuilder setTableInfo(TableEntity tableInfo) {
this.tableInfo = tableInfo;
return this;
}
public TemplateMapBuilder setColumnList(List<TableColumnsDO> columnList) {
this.columnList = columnList;
return this;
}
public TemplateMapBuilder setProjectRoot(String projectRoot) {
this.projectRoot = projectRoot;
return this;
}
public TemplateMapBuilder setTableName(String tableName) {
this.tableName = tableName;
return this;
}
public TemplateMapBuilder setProjectName(String projectName) {
this.projectName = projectName;
return this;
}
public TemplateMapBuilder setApiPackage(String apiPackage) {
this.apiPackage = apiPackage;
return this;
}
public TemplateMapBuilder setApiSaveDir(String apiSaveDir) {
this.apiSaveDir = apiSaveDir;
return this;
}
public TemplateMapBuilder setApiEnabled(boolean apiEnabled) {
this.apiEnabled = apiEnabled;
return this;
}
public TemplateMapBuilder setApiTemplate(String apiTemplate) {
this.apiTemplate = apiTemplate;
return this;
}
public TemplateMapBuilder setDtoEnabled(boolean dtoEnabled) {
this.dtoEnabled = dtoEnabled;
return this;
}
public TemplateMapBuilder setDtoPackage(String dtoPackage) {
this.dtoPackage = dtoPackage;
return this;
}
public TemplateMapBuilder setDtoSaveDir(String dtoSaveDir) {
this.dtoSaveDir = dtoSaveDir;
return this;
}
public TemplateMapBuilder setDtoTemplate(String dtoTemplate) {
this.dtoTemplate = dtoTemplate;
return this;
}
public TemplateMapBuilder setVoEnabled(boolean voEnabled) {
this.voEnabled = voEnabled;
return this;
}
public TemplateMapBuilder setVoPackage(String voPackage) {
this.voPackage = voPackage;
return this;
}
public TemplateMapBuilder setVoSaveDir(String voSaveDir) {
this.voSaveDir = voSaveDir;
return this;
}
public TemplateMapBuilder setVoTemplate(String voTemplate) {
this.voTemplate = voTemplate;
return this;
}
public TemplateMapBuilder setDaoEnabled(boolean daoEnabled) {
this.daoEnabled = daoEnabled;
return this;
}
public TemplateMapBuilder setDaoPackage(String daoPackage) {
this.daoPackage = daoPackage;
return this;
}
public TemplateMapBuilder setDaoSaveDir(String daoSaveDir) {
this.daoSaveDir = daoSaveDir;
return this;
}
public TemplateMapBuilder setDaoTemplate(String daoTemplate) {
this.daoTemplate = daoTemplate;
return this;
}
public TemplateMapBuilder setHibernateEnabled(boolean hibernateEnabled) {
this.hibernateEnabled = hibernateEnabled;
return this;
}
public TemplateMapBuilder setHibernatePackage(String hibernatePackage) {
this.hibernatePackage = hibernatePackage;
return this;
}
public TemplateMapBuilder setHibernateSaveDir(String hibernateSaveDir) {
this.hibernateSaveDir = hibernateSaveDir;
return this;
}
public TemplateMapBuilder setHibernateTemplate(String hibernateTemplate) {
this.hibernateTemplate = hibernateTemplate;
return this;
}
public TemplateMapBuilder setModelEnabled(boolean modelEnabled) {
this.modelEnabled = modelEnabled;
return this;
}
public TemplateMapBuilder setModelPackage(String modelPackage) {
this.modelPackage = modelPackage;
return this;
}
public TemplateMapBuilder setModelSaveDir(String modelSaveDir) {
this.modelSaveDir = modelSaveDir;
return this;
}
public TemplateMapBuilder setModelTemplate(String modelTemplate) {
this.modelTemplate = modelTemplate;
return this;
}
public TemplateMapBuilder setServiceImplEnabled(boolean serviceImplEnabled) {
this.serviceImplEnabled = serviceImplEnabled;
return this;
}
public TemplateMapBuilder setServiceImplPackage(String serviceImplPackage) {
this.serviceImplPackage = serviceImplPackage;
return this;
}
public TemplateMapBuilder setServiceImplSaveDir(String serviceImplSaveDir) {
this.serviceImplSaveDir = serviceImplSaveDir;
return this;
}
public TemplateMapBuilder setServiceImplTemplate(String serviceImplTemplate) {
this.serviceImplTemplate = serviceImplTemplate;
return this;
}
public TemplateMapBuilder setSysPackageName(String sysPackageName) {
this.sysPackageName = sysPackageName;
return this;
}
public TemplateMapBuilder setSysSaveDir(String sysSaveDir) {
this.sysSaveDir = sysSaveDir;
return this;
}
public TemplateMapBuilder setSysAutoModel(String sysAutoModel) {
this.sysAutoModel = sysAutoModel;
return this;
}
}
让我们看一下具体的调用代码吧
package com.srcgen;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import com.srcgen.builder.ParentConfig;
import com.srcgen.builder.TemplateMapBuilder;
import com.srcgen.dao.IAutoGenDAO;
import com.srcgen.domain.TableColumnsDO;
import com.srcgen.domain.entity.TableEntity;
import com.srcgen.utils.FileCreateUtils;
import freemarker.template.Template;
public class GenHelper {
/**
*
* @param projectRoot 系统地址 例如 F:/git-service
* @param tableName 表名 : CUSTOM_LINKMAN
* @param projectName 项目名 : winhc-mis-back
* @param dbName 数据库名 :firefly
* @param sysPackageName 保存的包名: com.winhc.mis
* @param sysSaveDir 保存的文件地址 /src/main/java/com/winhc/mis
* @param sysAutoModel 包名的地址 caseBaseInfo
* @throws Exception
*/
public static void genCodes(String projectRoot,String tableName,String projectName,String dbName,String sysPackageName,String sysSaveDir,String sysAutoModel) throws Exception {
BeanFactory beanFactory=new ClassPathXmlApplicationContext(new String[] {
"dao/autogen-mybatis-datasource.xml",
"dao/autogen-mybatis-dao.xml",
"root-context.xml"
});
System.out.println("..SRC AUTO GEN START..");
IAutoGenDAO iAutoGenDAO=(IAutoGenDAO)beanFactory.getBean("iAutoGenDAO");
FreeMarkerConfigurer freemarkerConfig=(FreeMarkerConfigurer)beanFactory.getBean("freemarkerConfig");
//freemarkerConfig.getConfiguration().
//foreach table name
TableEntity tableProfileDO=null;
List<TableColumnsDO> tableColumnsDOList=null;
//查询表
tableProfileDO=iAutoGenDAO.findTableProfile(tableName,dbName);
//查询表字段
tableColumnsDOList=iAutoGenDAO.listTableColumns(tableName,dbName);
Map<String,ParentConfig> map = new TemplateMapBuilder()
.setProjectRoot(projectRoot)
.setTableName(tableName)
.setProjectName(projectName)
.setTableInfo(tableProfileDO)
.setColumnList(tableColumnsDOList)
.setSysPackageName(sysPackageName)
.setSysSaveDir(sysSaveDir)
.setSysAutoModel(sysAutoModel)
.build();
for(String configKey:map.keySet()){
ParentConfig config = map.get(configKey);
Template template = freemarkerConfig.getConfiguration().getTemplate(config.getTemplateDir());
String tempStr=FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
//System.out.println(tempStr);
FileCreateUtils.saveSrcToUtf8File(config.getSaveDir()+config.getClassName()+ ".java", tempStr);
}
System.out.println("..SRC AUTO GEN END ..");
}
public static void main(String[] args) {
try {
genCodes("F:/idea-project-all",
"CUSTOM_LINKMAN",
"riskmanage1",
"firefly",
"com.winhc.flysky.riskmanage",
"/src/main/java/com/winhc/flysky/riskmanage",
"test1");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
以上就是我的整体思路啦,详细代码可以私信我,如若未能及时回复,请加我的wx:mzxf77获取git地址