您的位置:首页 > 编程语言

记mybatis.generator自动生成代码实现

2018-05-04 21:40 447 查看
版权声明:转载请标明出处 谢谢 https://blog.csdn.net/chijiandi/article/details/80200697

前言

在开发中直接嵌入此模块来简化使用工具类生成,由自动生成的代码可通过修改源码的方法来控制生成的内容。主要的增删改查等方法用例皆在生成包含内。

页面流程

完成后的页面长这样,页面数据很简单,通过查数据库表的一些信息即可
1.点生成按钮时生成一个dialog传入表名(不可修改),需要填写作者、pojo、mapper的所在路径。
2.点击dialog的生成,会在后台生成实体类以及mapper.java、mapper.xml
调用方法如下,加载配置文件,直接调用generate方法即可。

public void generator() throws Exception {
List<String> warnings = new ArrayList<>();
boolean overwrite = true;
//指定 逆向工程配置文件
URL url = getClass().getClassLoader().getResource("generatorConfig.xml");
//获取项目根目录存放临时文件
String savePath = ProjectPathUtil.getProjectPath()+"/codeCreate/";
MyUtils.deleteDir(savePath);

File file = new File(savePath);
if (!file.exists()) {
file.mkdir();
}
//主要用来获取context 设置属性
Configuration config = new ConfigurationParser(warnings).parseConfiguration(new File(url.getFile()));
for (Context context : config.getContexts()) {
setContext(context,savePath);
}

DefaultShellCallback callback = new DefaultShellCallback(overwrite);
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
myBatisGenerator.generate(null);
}

3.因为作者信息是封装在jar中的,尝试许久无法更改,所以这里通过生成后替换文件内容的作者信息完成。

String replaceAllMapper = codeCreate.getMapperURL().replaceAll("\\.", "/");
String mapperJava = sourcePath + "/" + replaceAllMapper + "/" + MyUtils.toUpperCaseFirst(codeCreate.getTableName().split("_")) + "Mapper.java";

String replaceAllPojo = codeCreate.getPojoURL().replaceAll("\\.", "/");
String pojoJava = sourcePath + "/" + replaceAllPojo + "/" + MyUtils.toUpperCaseFirst(codeCreate.getTableName().split("_")) + ".java";

//替换指定字符
MyUtils.propertiesChange(mapperJava, "Copyright(C)", "Copyright(C) " + codeCreate.getAuthor());
MyUtils.propertiesChange(pojoJava, "Copyright(C)", "Copyright(C) " + codeCreate.getAuthor());
MyUtils.propertiesChange(pojoJava, "@author", "@author " + codeCreate.getAuthor());

4.通过zip流将文件压缩,保存路径传给前端。

public static File zip(String filePath) {
File target = null;
File source = new File(filePath);
if (source.exists()) {
// 压缩文件名=源文件名.zip
String zipName = source.getName() + ".zip";
target = new File(source.getParent(), zipName);
if (target.exists()) {
target.delete(); // 删除旧的文件
}
FileOutputStream fos = null;
ZipOutputStream zos = null;
try {
fos = new FileOutputStream(target);
zos = new ZipOutputStream(new BufferedOutputStream(fos));
// 添加对应的文件Entry
addEntry("/", source, zos);
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
IOUtil.closeQuietly(zos, fos);
}
}
return target;
}

5.前端将请求跳转给文件下载,将zip包下载至本地。

前端通过下面语句进行下载(这种用法是因为ie浏览器的base属性在window.location.href不生效)

window.location = document.getElementsByTagName("base")[0].getAttribute("href") + "sys/file/download?path=" + data.data;

具体代码已上传至github
https://github.com/jiandi1027/newssm

阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: