实现entity、dao 、service 、serviceImpl自动生成

你。 提交于 2019-12-03 05:34:14

用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 {

	@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生成数据库表,根据自己的需求修改生成规则

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!