博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
实现entity、dao 、service 、serviceImpl自动生成
阅读量:6939 次
发布时间:2019-06-27

本文共 13086 字,大约阅读时间需要 43 分钟。

hot3.png

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

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

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

生成配置项:

/model.ftl
/dao.ftl
/service.ftl
com.wjw.xincms.server.service
com.wjw.xincms.server.dao
com.wjw.xincms.entity
User
用户
Role
角色

读取配置项,生成的实体、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
modellist = new ArrayList
(); //需要生成的实体对象集合 // 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
list) throws IOException, TemplateException{ path_Judge_Exist(filePath); //实体类需要其他参数 Map
root = new HashMap
(); 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
list) throws IOException, TemplateException { path_Judge_Exist(filePath); //实体类需要其他参数 Map
root = new HashMap
(); 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
list) throws IOException, TemplateException { String ImplFilePath = filePath + "\\impl"; path_Judge_Exist(filePath); path_Judge_Exist(ImplFilePath); Map
root = new HashMap
(); 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
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
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			}}

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

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

你可能感兴趣的文章
linux apache
查看>>
在CMD命令行下关闭进程的命令
查看>>
puppet学习笔记之安装与配置
查看>>
ROS教程(6)---×××配置及应用
查看>>
Nginx服务器搭建和基本配置详解
查看>>
vSphere 4.1 的新增功能
查看>>
栈的实现,入栈判断是否Full,出栈判断是否Empty
查看>>
nagios 安装配置
查看>>
centos 6.5下搭建ipsec/xl2tpd ×××
查看>>
【BFS】POJ 3278
查看>>
Python字符串格式化
查看>>
计算时针与分针夹角的度数的算法
查看>>
访问者设计模式
查看>>
支持伍洲彤鄙视蔡国庆
查看>>
我的友情链接
查看>>
Apache Shiro学习笔记(七)Servlet3.0 Listener介绍
查看>>
zabbix2
查看>>
我的友情链接
查看>>
char、varchar的区别
查看>>
[操作系统作业]os实验三:进程的管道通信
查看>>