2019独角兽企业重金招聘Python工程师标准>>>

用java代码编写工具类,实现entity、dao 、service 、serviceImpl自动生成。

参考开源csdn一位博友写的,改动了部分实现自己需求规则

http://blog.csdn.net/u010137431/article/details/46595487

生成配置项:

<?xml version="1.0" encoding="UTF-8"?><root><!-- 模板配置    模板文件路径和model、dao、service对应需要的模板名--><ftl path="\\src\\main\\java\\com\\wjw\\framework\\generate\\ftl"><param name="model">/model.ftl</param><param name="dao">/dao.ftl</param><param name="service">/service.ftl</param></ftl><!-- service.ftl需要的信息   path service包路径   packageName service中的java文件需要指定包名 --><service path="\\src\\main\\java\\com\\wjw\\xincms\\server\\service"><packageName>com.wjw.xincms.server.service</packageName></service><!-- dao.ftl需要的信息  path dao包路径  packageName dao中的java文件需要指定包名 --><dao path="\\src\\main\\java\\com\\wjw\\xincms\\server\\dao"><packageName>com.wjw.xincms.server.dao</packageName></dao><!-- model.ftl需要的信息  path model包路径   packageName model中的java文件需要指定包名    class 实体类名   desc 类名注释 --><models path="\\src\\main\\java\\com\\wjw\\xincms\\entity"><packageName>com.wjw.xincms.entity</packageName><model><className>User</className><desc>用户</desc></model><model><className>Role</className><desc>角色</desc></model></models>
</root>

读取配置项,生成的实体、dao、service的位置,需要生成的实体类等:

package com.wjw.framework.generate;import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import freemarker.template.TemplateException;public class Generate {public static void main(String[] args) throws IOException, TemplateException, ParserConfigurationException, SAXException {String ftlPath = ""; //模板路径//model参数String ModelftlName = "";  //model模板名称String ModelfilePath = ""; //模板路径String ModelpackgeName = "";//模板包名List<Attr> modellist = new ArrayList<Attr>(); //需要生成的实体对象集合// dao参数String DaoftlName = ""; //dao模板名称String DaofilePath = ""; //dao路径String DaopackgeName = ""; //dao包名//service参数String ServiceftlName = ""; //Service模板名称String ServicefilePath = ""; //service路径String ServicepackgeName = "";//service包名//配置文件位置File  xmlFile = new File(System.getProperty("user.dir"), "\\src\\main\\java\\com\\wjw\\framework\\generate\\GenerateConf.xml");DocumentBuilderFactory  builderFactory =  DocumentBuilderFactory.newInstance();  DocumentBuilder   builder = builderFactory.newDocumentBuilder();  Document  doc = builder.parse(xmlFile);Element rootElement = doc.getDocumentElement(); //获取根元素Node ftlnode = rootElement.getElementsByTagName("ftl").item(0);ftlPath = ((Element)ftlnode).getAttribute("path");NodeList params = ftlnode.getChildNodes();for(int i = 0; i < params.getLength(); i++){//获取对应模板名称Node node = params.item(i);if(node.getNodeType() != Node.ELEMENT_NODE) continue;Element e = (Element)node;if(e.getAttribute("name").trim().equals("model"))  ModelftlName = node.getFirstChild().getNodeValue();if(e.getAttribute("name").trim().equals("dao"))  DaoftlName = node.getFirstChild().getNodeValue();if(e.getAttribute("name").trim().equals("service"))  ServiceftlName = node.getFirstChild().getNodeValue();}//获取对应service参数Node servicenode = rootElement.getElementsByTagName("service").item(0);ServicefilePath = ((Element)servicenode).getAttribute("path");ServicepackgeName = servicenode.getChildNodes().item(1).getFirstChild().getNodeValue();//获取对应dao参数Node daonode = rootElement.getElementsByTagName("dao").item(0);DaofilePath = ((Element)daonode).getAttribute("path");DaopackgeName = daonode.getChildNodes().item(1).getFirstChild().getNodeValue();//获取对应model参数Node modelnode = rootElement.getElementsByTagName("models").item(0);ModelfilePath = ((Element)modelnode).getAttribute("path");params = modelnode.getChildNodes();for(int i = 0; i < params.getLength(); i++){Node node = params.item(i);if(node.getNodeType() != Node.ELEMENT_NODE) continue;Element e = (Element)node;if(e.getNodeName().trim().equals("packageName")) ModelpackgeName = node.getFirstChild().getNodeValue();if(e.getNodeName().trim().equals("model")){Attr attr = new Attr();NodeList attrnode = node.getChildNodes();for(int j = 0; j < attrnode.getLength(); j++){Node anode = attrnode.item(j);if(anode.getNodeType() != Node.ELEMENT_NODE) continue;Element ae = (Element)anode;if(ae.getTagName().trim().equals("className")) attr.setClassName(anode.getFirstChild().getNodeValue());if(ae.getTagName().trim().equals("desc")) attr.setDesc(anode.getFirstChild().getNodeValue());}modellist.add(attr);}}GenerateUtil gt =new GenerateUtil("wjw",ftlPath);gt.GenerateDao(DaoftlName, DaofilePath, DaopackgeName, ModelpackgeName,modellist);gt.GenerateService(ServiceftlName, ServicefilePath, ServicepackgeName, DaopackgeName, ModelpackgeName,modellist);gt.GenerateModel(ModelftlName, ModelfilePath, ModelpackgeName, modellist);}
}

GenerateUtil gt =new GenerateUtil("wjw",ftlPath);//传入生成的作者名 ,生成模板路径

//生成model实体类

gt.GenerateModel(ModelftlName, ModelfilePath, ModelpackgeName, modellist);

//生成dao

gt.GenerateDao(DaoftlName, DaofilePath, DaopackgeName, ModelpackgeName,modellist);

//生成service和serviceImpl实现

gt.GenerateService(ServiceftlName, ServicefilePath, ServicepackgeName, DaopackgeName, ModelpackgeName,modellist);
获取需要生成的参数传入freemarker模板中,写入到指路径下

package com.wjw.framework.generate;import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;import org.wjw.utils.DateUtil;
import org.wjw.utils.HumpUtils;import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;/*** @desc 生成工具类* @author wjw* @date 2016年12月21日下午4:31:29*/
public class GenerateUtil {public String author="wjw";//设置默认作者public String ftlPath;//模板所在路径public GenerateUtil() {}public GenerateUtil(String author,String ftlPath) {this.author = author;this.ftlPath = ftlPath;path_Judge_Exist(ftlPath);}/*** @desc  model生成方法* @param ftlName      模板名* @param filePath       model层的路径* @param packageName  model包名* @param list           model参数集合*/public void GenerateModel(String ftlName, String filePath, String packageName, List<Attr> list) throws IOException, TemplateException{path_Judge_Exist(filePath);//实体类需要其他参数Map<String,Object> root = new HashMap<String, Object>();root.put("packageName", packageName);root.put("author", author);for(Attr a : list){String className = a.getClassName();root.put("desc", a.getDesc());root.put("createDate", DateUtil.formatDate(new Date(), "yyyy年MM月dd日aK:mm:ss") );root.put("className", className);root.put("table",  HumpUtils.camelToUnderline2(className));Configuration cfg = new Configuration();String path = System.getProperty("user.dir") + ftlPath;cfg.setDirectoryForTemplateLoading(new File(path));Template template = cfg.getTemplate(ftlName);printFile(root, template, filePath, className);}}/*** @desc  dao生成方法* @param ftlName* @param filePath* @param packageName* @param modelPackageName* @param list* @throws IOException* @throws TemplateException*/public void GenerateDao(String ftlName, String filePath, String packageName, String modelPackageName,List<Attr> list) throws IOException, TemplateException {path_Judge_Exist(filePath);//实体类需要其他参数Map<String,Object> root = new HashMap<String, Object>();root.put("packageName", packageName);root.put("author", author);root.put("modelPackageName", modelPackageName);for(Attr a : list){String modelClassName = a.getClassName();root.put("modelClassName", modelClassName);root.put("desc", a.getDesc());root.put("createDate", DateUtil.formatDate(new Date(), "yyyy年MM月dd日aK:mm:ss") );Configuration cfg = new Configuration();String path = System.getProperty("user.dir") + ftlPath;cfg.setDirectoryForTemplateLoading(new File(path));Template template = cfg.getTemplate(ftlName);printFile(root, template, filePath, modelClassName + "Dao");}}/*** @desc servic接口和实现的生成方法* @param ftlName* @param filePath* @param packageName* @param daoPackageName* @param modelPackageName* @param list* @throws IOException* @throws TemplateException*/public void GenerateService(String ftlName,String filePath, String packageName,String daoPackageName, String modelPackageName,List<Attr> list) throws IOException, TemplateException {String ImplFilePath = filePath + "\\impl";path_Judge_Exist(filePath);path_Judge_Exist(ImplFilePath);Map<String,Object> root = new HashMap<String, Object>();root.put("author", author);root.put("daoPackageName", daoPackageName);root.put("packageName", packageName);root.put("implPackageName", packageName+".impl");root.put("modelPackageName", modelPackageName);for(Attr a : list){String className = a.getClassName();//类名root.put("desc", a.getDesc());root.put("createDate", DateUtil.formatDate(new Date(), "yyyy年MM月dd日aK:mm:ss") );root.put("className", className);root.put("implflag", false);//接口Configuration cfg = new Configuration();String path = System.getProperty("user.dir") + ftlPath;cfg.setDirectoryForTemplateLoading(new File(path));Template template = cfg.getTemplate(ftlName);printFile(root, template, filePath, className + "Service");//生成service接口root.put("implflag", true);//实现printFile(root, template, ImplFilePath, className + "ServiceImpl");//生成service实现}}//判断包路径是否存在public static void path_Judge_Exist(String path){File file = new File(System.getProperty("user.dir"), path);if(!file.exists()) file.mkdirs();}//输出到文件public static void printFile(Map<String, Object> root, Template template, String filePath, String fileName) throws IOException, TemplateException  {String path = System.getProperty("user.dir") + filePath;File file = new File(path, fileName + ".java");if(!file.exists()) file.createNewFile();FileWriter fw = new FileWriter(file);template.process(root, fw);fw.close();}//输出到控制台public static void printConsole(Map<String, Object> root, Template template)throws TemplateException, IOException {StringWriter out = new StringWriter();template.process(root, out);System.out.println(out.toString());}public String getAuthor() {return author;}public void setAuthor(String author) {this.author = author;}public String getFtlPath() {return ftlPath;}public void setFtlPath(String ftlPath) {this.ftlPath = ftlPath;}
}

下面贴出模板model、dao、service模板:

package ${packageName};import javax.persistence.Entity;
import javax.persistence.Table;import com.wjw.framework.spring.persistence.BaseEntity;/*** @desc ${desc}-实体类* @author ${author}* @date ${createDate}*/
@Entity
@Table(name = "${table}")
public class ${className} extends BaseEntity {}
package ${packageName};import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;import ${modelPackageName}.${modelClassName};/*** @desc ${desc}-Dao* @author ${author}* @date ${createDate}*/
public interface ${modelClassName}Dao extends PagingAndSortingRepository<${modelClassName}, String>, JpaSpecificationExecutor<${modelClassName}> {}
<#if !implflag>
package ${packageName};import ${modelPackageName}.${className};/*** @desc ${desc}-服务接口* @author ${author}* @date ${createDate}*/
public interface ${className}Service {public void save(${className} ${className?lower_case});}
<#else>
package ${implPackageName};import ${modelPackageName}.${className};
import ${daoPackageName}.${className}Dao;
import ${packageName}.${className}Service;import org.springframework.beans.factory.annotation.Autowired;/*** @desc ${desc}-服务实现* @author ${author}* @date ${createDate}*/
public class  ${className}ServiceImpl implements  ${className}Service {@Autowiredprivate ${className}Dao ${className?lower_case}Dao;@Overridepublic void save(${className} ${className?lower_case}) {// TODO Auto-generated method stub}}
</#if>

下面是接收需要生成的实体对象类:

package com.wjw.framework.generate;public class Attr {private String className;  //类名private String desc; //描述public Attr() {// TODO Auto-generated constructor stub}public Attr(String className,String desc) {this.className=className;this.desc=desc;}public String getClassName() {return className;}public void setClassName(String className) {this.className = className;}public String getDesc() {return desc;}public void setDesc(String desc) {this.desc = desc;}}

最后生成的代码截图

可根据自己用的框架来修改模板实现自己的需求。

我去掉了具体的字段生成,在需求中字段是经常增加修改的,添加几个字段用eclipse的快捷键shirt+alt+s也能快速生成set、get方法,通过数据库生成实体类我用不到,我的是实体类通过hibernate生成数据库表,根据自己的需求修改生成规则

转载于:https://my.oschina.net/u/1377077/blog/809837

实现entity、dao 、service 、serviceImpl自动生成相关推荐

  1. 自动生成Android界面,面向Android的Web Service界面自动生成技术研究

    摘要: 据统计,开发人员在开发应用程序的过程中,接近一半的代码用于用户界面部分,大约一半的运行时间用于执行这一部分.所以,减少用户界面部分的开发代码和运行时间,能有效提高程序的运行效率.智能家居中,由 ...

  2. 实际开发中 dao、entity的代码怎样自动生成?一款工具送给你

    01 关注"一猿小讲"朋友,都知道以往的文章一直倡导拒绝 CRUD,那到底什么是 CRUD?今天咱们就聊聊 Java 妹子小猿与数据库老头交互的事儿. 产品小汪铿锵有力的说:小猿同 ...

  3. java dao层代码生成器_实际开发中 dao、entity的代码怎样自动生成?一款工具送给你...

    01 关注"一猿小讲"朋友,都知道以往的文章一直倡导拒绝 CRUD,那到底什么是 CRUD?今天咱们就聊聊 Java 妹子小猿与数据库老头交互的事儿. 产品小汪铿锵有力的说:小猿同 ...

  4. EasyCode插件(自动生成代码神器)

    简介 在传统的项目中,数据库写好以后,需要手动写对应的实体类,DAO层接口,Service接口,以及数据库的映射文件,数据库的表不多的话还好说,如果动则几十张表,上百张表,每个表都得写对应的文件,就显 ...

  5. Java进阶之 如何自动生成代码

    一.前言:为什么要有代码的自动生成?     对于这个问题 最简洁直接的回答就是:代替手动编写代码.提高工作效率. 什么样的场景和代码适合用自动生成这种方式呢?     做过Java服务端的朋友一定都 ...

  6. php lmpl,tjx-cold: 用于根据配置模板,快速生成controller,service,serviceimpl 代码

    用于根据配置模板,快速生成controller,service,serviceimpl 代码(交流群 623169994 ) 为什么要开发这款插件 市面上有很多基于数据库生成代码的工具,但是我自己的工 ...

  7. 使用MyBatis Generator自动生成实体、mapper和dao层

    原文链接 通过MyBatis Generator可以自动生成实体.mapper和dao层,记录一下怎么用的. 主要步骤: 关于mybatis从数据库反向生成实体.DAO.mapper: 参考文章:ht ...

  8. idea + groovy + mybatis 自动生成 Dao、mappings 和 实体类

    背景 在 windows 系统中,idea 在 C:\Users\用户名\.IntelliJIdea2018.2\config\extensions\com.intellij.database\sch ...

  9. mybatis 自动生成dao mapper 文件

    <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE generatorConfiguratio ...

最新文章

  1. FragmentManager中Fragment的重复创建、复用问题
  2. makefile 和shell文件相互调用
  3. linux怎么用两个进程传值,linux下的C开发14,可执行程序如何传递参数?模拟shell执行命令...
  4. 给脚本添加到环境变量_让你的脚本可以在任意地方都可执行的几个方法
  5. Docker 制作自定义化的Tomcat镜像
  6. MS speech SDK5.1朗读控件
  7. ws2812b程序51单片机_51单片机串口通信程序详解
  8. bzoj1449 [JSOI2009]球队收益
  9. MTK 驱动开发(3)---GPIO口的使用方法汇总
  10. 《Essential C++》笔记之传指针(pass by pointer)分析
  11. Window CE 驱动开发流程(Windows CE.5.0系统、pxa270平台)
  12. 深度 | 朴素贝叶斯模型算法研究与实例分析
  13. HTML:常用特殊字符编码表(自用)
  14. 如何长时间保存记忆,分享我的数据备份大法
  15. 二级等保和三级等保区别,企业单位要做几级?甜甜告诉您
  16. 水务信息化数据整合系统方案分析
  17. 专注世界排名的Alexa.com宣布关站
  18. 计算机二级选择题需要刷吗,“我明天就要考计算机二级了”
  19. 腾讯王卡运营坑之一:web容器优雅停机缓慢
  20. 单臂路由配置-ZTE中兴交换机

热门文章

  1. 计算机科学与技术第6次上机实验报告,计算机科学与技术第次实验报告-20210602214116.docx-原创力文档...
  2. 微型计算机外文文献,电子信息科学与技术专业Microcomputer-Systems微型计算机控制系统大学毕业论文外文文献翻译及原文.doc...
  3. mysql 中文的数据类型_mysql数据类型整理
  4. python2.7环境下“No module named matplotlib.pyplot”的解决办法
  5. 【 MATLAB 】离散傅里叶级数(DFS)及 IDFS 的 MATLAB 实现
  6. IE 8兼容:meta http-equiv=X-UA-Compatible content=IE=edge / X-UA-Compatible的解释
  7. 浅谈高风险多团队协同的项目管理方法
  8. iOS 之 事件响应者链
  9. 文本文件变身电子表格
  10. 微软忘记修复Mac Office2004/2008安全漏洞