前言
公司在做一些基础的功能 不需要重复去操作 比如说单表的增删改查业务代码从controller->service->dao层的相关代码都可以不用程序员去手动编写每一行代码,能更好的利用工具很好的生成。
一:引入依赖
xml
<!-- 添加freemarker依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
二:案例展示
java
private void createSource(CodeCreate codeCreate) {
CodePrj cp = codePrjService.get(codeCreate.getCode());
PrjDs ds = prjDsService.get(cp.getPrjId(), codeCreate.getDsCode());
DbDs dbDs = DbDsUtil.getDbds(ds, codeCreate.getDbName());
List<String> tableList = FrameStringUtil.toArray(codeCreate.getTables(), ",");
List<CodeTemplate> cts = codeTemplateService.findByCode(codeCreate.getCode());
String createPathDir = EnvUtil.get(Env.CODE_SOURCE_PATH);
String dateString = FrameTimeUtil.parseString(FrameTimeUtil.getTime(), FrameTimeUtil.FMT_YYYYMMDDHHMMSS);
String createPath = File.separator + codeCreate.getCode() + File.separator + dateString;
for (String tableName : tableList) {
Table table = dbDs.getTable(tableName);
for (CodeTemplate template : cts) {
String suffix = "." + CodeTemplateType.getText(template.getType());
String curCreatePath = createPath + File.separator;
if(CodeTemplateType.JAVA.getCode() == template.getType().intValue() ||
CodeTemplateType.XML.getCode() == template.getType().intValue()) {
String pk = codeCreate.getPackagePath() + "." + template.getPackageName();
String fileSuffix = template.getSuffix();
curCreatePath += "src" + File.separator + CodeFileUtil.getFolder(pk) + File.separator + table.getClassName() + FrameStringUtil.setFirstCharUpcase(fileSuffix) + suffix;
} else {
curCreatePath += "webapp" + File.separator + table.getBeanName() + "-" + template.getPackageName() + suffix;
}
CodeFileUtil.process(getDescMap(table, codeCreate.getPackagePath()), EnvUtil.get(Env.CODE_TEMPLATE_PATH) + template.getPath(), createPathDir + curCreatePath);
}
}
dbDs.close();
//修改为生成完成 生成zip
String download = createPath + ".zip";
String sourcePath = createPathDir + createPath;
String zipPath = createPathDir + File.separator + codeCreate.getCode() + File.separator + dateString + ".zip";
boolean flag = FrameZipUtil.createZip(sourcePath, zipPath);
if(flag) {
codeCreateDao.updateFinish(codeCreate.getId(), download);
LOGGER.info("文件打包成功!");
} else {
LOGGER.info("文件打包失败!");
}
codeCreateDao.updateFinish(codeCreate.getId(), download);
}
核心代码块
java
public class DbDsUtil {
public static DbDs getDbds(PrjDs ds, String dbName) {
DbDs dbDs = null;
if(PrjDsType.MYSQL.getCode().equals(ds.getType())) {
dbDs = new MysqlDs();
} else if(PrjDsType.ORACLE.getCode().equals(ds.getType())) {
dbDs = new OracleDs();
}
dbDs.init(ds.getDriverClass(), ds.getUrl(), ds.getUsername(), ds.getPassword(), dbName);
return dbDs;
}
}
初始化不同数据库链接方式
java
public DsUtil init(String driverClass, String jdbcUrl,
String username, String password, String dbName) {
this.dbName = dbName;
Integer initialSize = 10;
Integer maxIdle = 20;
Integer minIdle = 5;
dsUtil = new DsUtil();
dsUtil.init(driverClass, jdbcUrl, username, password, initialSize, maxIdle, minIdle, true);
return dsUtil;
}
java
public void init(String driverClass, String jdbcUrl,
String username, String password, Integer initialSize,
Integer maxIdle, Integer minIdle, boolean isSetDs) {
if(initialSize == null) {
initialSize = 10;
}
if(maxIdle == null) {
maxIdle = 30;
}
if(minIdle == null) {
minIdle = 10;
}
dataSource = new DruidDataSource();
dataSource.setDriverClassName(driverClass);
dataSource.setUrl(jdbcUrl);
dataSource.setUsername(username);
dataSource.setPassword(password);
dataSource.setInitialSize(initialSize);
dataSource.setMaxActive(maxIdle);
dataSource.setMinIdle(minIdle);
if(isSetDs) {
setDs();
}
}
java
/**
* 设置数据源
* @return
*/
public ResponseFrame setDs() {
ResponseFrame frame = new ResponseFrame();
if(isInit) {
frame.setSucc();
return frame;
}
try {
dataSource.init();
} catch (SQLException e) {
frame.setCode(-3);
frame.setMessage(e.getMessage());
return frame;
}
jdbcTemplate = new JdbcTemplate(dataSource);
setJdbcTemplate(jdbcTemplate);
frame.setSucc();
return frame;
}
java
/**
* 根据模板生成相应的文件
* @param map 保存数据的map
* @param template 模板文件的地址
* @param path 生成的文档输出地址
* @return
*/
public static synchronized File process(Map<?, ?> map, String template, String path) {
if (null == map ) {
throw new RuntimeException("数据不能为空");
}
if (null == template) {
throw new RuntimeException("模板文件不能为空");
}
if (null == path) {
throw new RuntimeException("输出路径不能为空");
}
int templatePathIndex = template.lastIndexOf("/");
if(templatePathIndex == -1) {
templatePathIndex = template.lastIndexOf(File.separator);
}
String templatePath = template.substring(0, templatePathIndex);
FrameFileUtil.createDir(templatePath);
String templateName = template.substring(templatePathIndex + 1, template.length());
if (null == configuration) {
//这里Configurantion对象不能有两个,否则多线程访问会报错
configuration = new Configuration(Configuration.VERSION_2_3_23);
configuration.setDefaultEncoding("utf-8");
configuration.setClassicCompatible(true);
}
try {
configuration.setDirectoryForTemplateLoading(new File(templatePath));
} catch (Exception e) {
configuration.setClassForTemplateLoading(CodeFileUtil.class, templatePath);
}
/*int pathIndex = path.lastIndexOf("/");
if(pathIndex == -1) {
pathIndex = path.lastIndexOf("\\");
}*/
//String pathDir = path.substring(0, pathIndex);
File file = new File(path);
FrameFileUtil.createDir(file);
try {
Template t = null;
t = configuration.getTemplate(templateName);
Writer w = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "utf-8"));
// 这里w是一个输出地址,可以输出到任何位置,如控制台,网页等
t.process(map, w);
w.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
return file;
}
模版如下所示
xml
<?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="${packagePath}.dao.${table.className}Dao">
<sql id="commCols">
<#list table.columns as column>${column.columnName} ${column.fieldName}<#if column_has_next>,</#if></#list>
</sql>
<insert id="save" parameterType="${table.beanName}" flushCache="true">
insert into ${table.name}(<#list table.columns as column>${column.columnName}<#if column_has_next>,</#if></#list>)
values(<#list table.columns as column><#if (column.fieldName == "isDel")>0<#elseif (column.fieldName == "createTime")>now()<#else>${r"#{"}${column.fieldName}${r"}"}</#if><#if column_has_next>,</#if></#list>)
</insert>
<delete id="delete" flushCache="true">
delete from ${table.name}
<where>${table.firstKColumn.columnName}=${r"#{"}${table.firstKColumn.fieldName}${r"}"}</where>
</delete>
<update id="update" parameterType="${table.beanName}" flushCache="true">
update ${table.name}
<set>
<#list table.columns as column><#if (column.fieldName != table.firstKColumn.fieldName && column.fieldName != "isdel" && column.fieldName != "createUserId" && column.fieldName != "createTime" && column.fieldName != "companyid")><#if (column_index > 1)>,</#if>${column.columnName}=${r"#{"}${column.fieldName}${r"}"}</#if></#list>
</set>
<where>${table.firstKColumn.columnName}=${r"#{"}${table.firstKColumn.fieldName}${r"}"}</where>
</update>
<select id="get" resultType="${table.beanName}">
select <include refid="commCols"/> from ${table.name}
<where>${table.firstKColumn.columnName}=${r"#{"}${table.firstKColumn.fieldName}${r"}"}</where>
</select>
<sql id="whereFind${table.className}">
<where>
<if test="name!=null and name!=''">and name like concat(concat('%', ${r"#{name}"}), '%')</if>
</where>
</sql>
<select id="find${table.className}" parameterType="${table.beanName}" resultType="${table.beanName}">
select <include refid="commCols"/> from ${table.name}
<include refid="whereFind${table.className}"></include>
<choose>
<when test="orderbys!=null and orderbys.size()>0">
order by <foreach collection="orderbys" item="item" index="index" open="" separator="," close="">
${r"${item.property}"} ${r"${item.type}"}
</foreach>
</when>
<otherwise></otherwise>
</choose>
limit ${r"#{currentIndex}"}, ${r"#{size}"}
</select>
<select id="find${table.className}Count" parameterType="${table.beanName}" resultType="int">
select count(*) from ${table.name}
<include refid="whereFind${table.className}"></include>
</select>
</mapper>
java
public static boolean createZip(String sourcePath, String zipPath) {
FileOutputStream fos = null;
ZipOutputStream zos = null;
try {
fos = new FileOutputStream(zipPath);
zos = new ZipOutputStream(fos);
writeZip(new File(sourcePath), "", zos);
return true;
} catch (FileNotFoundException e) {
LOGGER.error("创建ZIP文件失败", e);
} finally {
try {
if (zos != null) {
zos.close();
}
} catch (IOException e) {
LOGGER.error("创建ZIP文件失败", e);
}
}
return false;
}
java
private static void writeZip(File file, String parentPath, ZipOutputStream zos) {
if (file.exists()) {
if (file.isDirectory()) {
parentPath = parentPath + file.getName() + File.separator;
File[] files = file.listFiles();
for(File f : files) {
writeZip(f, parentPath, zos);
}
} else {
FileInputStream fis = null;
DataInputStream dis = null;
try {
fis = new FileInputStream(file);
dis = new DataInputStream(new BufferedInputStream(fis));
ZipEntry ze = new ZipEntry(parentPath + file.getName());
zos.putNextEntry(ze);
byte[] content = new byte[1024];
int len;
while((len = fis.read(content)) != -1) {
zos.write(content, 0, len);
zos.flush();
}
} catch (FileNotFoundException e) {
LOGGER.error("创建ZIP文件失败", e);
} catch (IOException e) {
LOGGER.error("创建ZIP文件失败", e);
} finally {
try {
if (dis != null) {
dis.close();
}
} catch (IOException e) {
LOGGER.error("创建ZIP文件失败", e);
}
}
}
}
}
java
public static void main(String[] args) {
String sourcePath = "E:\\monitor\\source\\7\\20170727165640";
String zipPath = "E:\\monitor\\source\\7\\20170727165640.zip";
createZip(sourcePath, zipPath);
}
好了 至此 spring之添加freemarker模版熏染 点点关注不迷路 老铁们!!!!!