用java代碼編寫工具類,實現entity、dao 、service 、serviceImpl自動生成。java
參考開源csdn一位博友寫的,改動了部分實現本身需求規則node
http://blog.csdn.net/u010137431/article/details/46595487spring
生成配置項:數據庫
<?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);//傳入生成的做者名 ,生成模板路徑dom
//生成model實體類eclipse
gt.GenerateModel(ModelftlName, ModelfilePath, ModelpackgeName, modellist);ide
//生成dao工具
gt.GenerateDao(DaoftlName, DaofilePath, DaopackgeName, ModelpackgeName,modellist);ui
//生成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 { @Autowired private ${className}Dao ${className?lower_case}Dao; @Override public 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生成數據庫表,根據本身的需求修改生成規則