`

Spring dao 和Service 生成文件类

 
阅读更多
package com.annotationtodaotoservice;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

/**
 * @see  生成dao 和service 文件和文件夹
 * @author liuqing
 * @since  2011-5-1
 * @version 1.0
 */
public class DaoServiceImpl {

    private Logger log = Logger.getLogger(DaoServiceImpl.class.getName());

    private String entityDir;

    public static void main(String args[]) throws Exception {
    	
        DaoServiceImpl dao = new DaoServiceImpl();
       
        dao.entityDir = "D:\\cache\\entity";
        dao.packageToFile("dao.impl");
        dao.packageToFile("service.impl");
        Map<String,List<File>> fileMap = dao.entityFileToDaoFile();
        List<File> daoFile = fileMap.get("dao");
        List<File> daoImplFile = fileMap.get("daoImpl");
        List<File> serviceFile = fileMap.get("service");
        List<File> serviceFileImpl = fileMap.get("serviceImpl");
        OutputStream out = null;
        dao.outFileDaoAndService(daoFile,out,1);
        dao.outFileDaoAndService(daoImplFile,out,2);
        dao.outFileDaoAndService(serviceFile,out,3);
        dao.outFileDaoAndService(serviceFileImpl,out,4);
        if (out != null) {
        	out.close();
        }
        
    }

    public void outFileDaoAndService(List<File> files,OutputStream out,int type)
            throws FileNotFoundException {
        for (File fileName:files) {
            out = new FileOutputStream(fileName);
            this.print(out, type, fileName.getName());
        }
    }
    
    public String toLowerFirst(String str) {
    	if (str != null && !"".equals(str)) {
    		char ch[] = str.toCharArray();
    		if (ch.length > 0) {
    			if (ch[0] < 'a') {
    				ch[0] = (char) (ch[0] + 32);
    			}
    		}
    		return (new String(ch));
    	}
    	return str;
    }
    
    public String toUpFirst(String str) {
    	if (str != null && !"".equals(str)) {
    		char ch[] = str.toCharArray();
    		if (ch.length > 0) {
    			if (ch[0] > 'Z') {
    				ch[0] = (char) (ch[0] - 32);
    			}
    		}
    		return (new String(ch));
    	}
    	return str;
    }

    /**
     *
     * @param out
     * @param typeInfo 1:为IDao 2 DaoImpl 3 IService 4 ServiceImpl
     */
    public void print(OutputStream output,int typeInfo,String clazzName) {

        PrintWriter out = new PrintWriter(output);
        if (typeInfo == 1) {
            this.fileToDao(this.javaFileToClassName(clazzName), out, " com.bs.phs.dao.jkjy");
        }
        else if (typeInfo == 2) {
            this.fileToDaoImpl(this.javaFileToClassName(clazzName), out, " com.bs.phs.dao.jkjy.impl");
        }
        else if (typeInfo == 3) {
            this.fileToService(this.javaFileToClassName(clazzName), out, " com.bs.phs.service.jkjy");
        }
        else {
            this.fileToServiceImpl(this.javaFileToClassName(clazzName), out, " com.bs.phs.service.jkjy.impl");
        }
        out.flush();
        
    }

    public void fileToDao(String clazzName,PrintWriter out,String packageInfo) {
        out.println("package " + packageInfo + ";");
        out.println("");
      //  out.println("import " + packageInfo +"." + clazzName + ";");
        this.toLogger(clazzName, out, packageInfo);
        out.println("public interface " + clazzName +
                " extends IBaseDao<" + this.daoService(clazzName,1) + "> {");
        out.println();
        out.println("}");
        out.flush();
    }

    /**
     * 文件头部信息日志
     * @param clazzName
     * @param out
     * @param packageInfo
     */
    public void toLogger(String clazzName,PrintWriter out,String packageInfo) {
        out.println();
        out.println("/**");
        out.println(" * @since " + packageInfo + "." + clazzName + ".java");
        out.println(" * @see  " +
                clazzName + " create datetime:" + dateToString()
                + "");
        out.println(" * @author liuqing");
        out.println(" * @version 1.0");
        out.println(" */");
    }

    public void fileToDaoImpl(String clazzName,PrintWriter out,String packageInfo) {
        out.println("package " + packageInfo + ";");
        out.println("");
        out.println("import " + packageInfo +"." + clazzName + ";");
        this.toLogger(clazzName, out, packageInfo);
        out.println("@Repository(\"" +
        		this.toLowerFirst(clazzName).substring(0, clazzName.length() - 4) +
        		"\")");
        out.println("public class " + clazzName +
                " extends BaseDaoImpl<" + this.daoService(clazzName,2) + "> implements " +
                "I" + this.daoService(clazzName, 2) +
                "Dao {");
        out.println();
        out.println("}");
        out.flush();
    }

    public void fileToService(String clazzName,PrintWriter out,String packageInfo) {
        out.println("package " + packageInfo + ";");
        out.println("");
        out.println("import " + packageInfo +"." + clazzName + ";");
        this.toLogger(clazzName, out, packageInfo);
        out.println("public interface " + clazzName +
                " extends IBaseService<" + this.daoService(clazzName,3) + "> {");
        out.println();
        out.println("}");
        out.flush();
    }

    /**
     * UsbServiceImpl
     * @param clazzName
     * @param out
     * @param packageInfo
     */
    public void fileToServiceImpl(String clazzName,PrintWriter out,String packageInfo) {
        out.println("package " + packageInfo + ";");
        out.println("");
        out.println("import " + packageInfo +"." + clazzName + ";");
        this.toLogger(clazzName, out, packageInfo);
        out.println("@Transactional");
        out.println("@Service(\"" + this.toLowerFirst(clazzName).substring(0, clazzName.length() - 4) + "\")");
        out.println("public class " + clazzName +
                " extends BaseServiceImpl<" + this.daoService(clazzName,4) + "> implements " +
                "I" + this.daoService(clazzName,4) + "Service" +
                " {");
        out.println("");
        String annotationName = clazzName.substring(0, clazzName.length() - 4);
        out.println("");
        String daoName = annotationName.substring(0, annotationName.length() - 7) + "Dao";
        out.println("@Resource(name=\"" + this.toLowerFirst(daoName) + "\")");
        out.println("private I" + this.toUpFirst(daoName) + " " + this.toLowerFirst(daoName) +";");
        out.println("");
        out.println("@Override");
        out.println("public IBaseDao<" +
        		this.toUpFirst(daoName.substring(0, daoName.length() - 3)) +
        		"> getTargetDao() {");
        out.println("    return " + this.toLowerFirst(daoName) + ";");
        out.println("}");
        out.println("");
        
        out.println("}");
        out.flush();

    }
    
    /**
     *  根据文件生成 ClassName
     * @param inclassName
     * @param typeInfo 1:为IDao 2 DaoImpl 3 IService 4 ServiceImpl
     * @return
     */
    public String daoService(String inclassName,int typeInfo) {
        int classLength = inclassName.length();
        if (typeInfo == 1) {
            return inclassName.substring(1, classLength - 3);
        }
        else if (typeInfo == 2){
            return inclassName.substring(0, classLength - 7);
        }
        else if (typeInfo == 3){
            return inclassName.substring(1, classLength - 7);
        }
        else {
            return inclassName.substring(0, classLength - 11);
        }
    }

    /**
     * 找到entityFile
     * @param covertDao
     * @param packageInfo
     * @throws FileNotFoundException
     */
    public File[] entityFileDir ()
            throws FileNotFoundException {
        List<File> files = new ArrayList<File>();
        File entityDirInfo = new File(entityDir);
        //新生成File类型
        File[] newFiles = new File[]{};
        File[] entityFiles = entityDirInfo.listFiles();
        entityDirInfo.mkdirs();
        	for (File f:entityFiles) {
        		if (f.getName().endsWith(".java")) {
        			files.add(f);
        			//System.out.println("---" + f.getName());
        		}
        	}
       return files.toArray(newFiles);
    }

    /**
     * 通过实体文件生成dao 和 service 文件
     * @param entityDir
     * @param typeInfo
     */
    public Map<String,List<File>> entityFileToDaoFile()
            throws FileNotFoundException {
        Map<String,List<File>> fileMap = new HashMap<String,List<File>>();
        List<File> dao = new ArrayList<File>();
        List<File> daoImpl = new ArrayList<File>();
        List<File> service = new ArrayList<File>();
        List<File> serviceImpl = new ArrayList<File>();
        File[] entityFiles = this.entityFileDir();
        for (File enFile:entityFiles) {
            int pos = enFile.getName().indexOf(".");
            String fileName = enFile.getName();
            String daoFileName = "I" + fileName.substring(0, pos) + "Dao.java";
            String daoImplFileName = fileName.substring(0, pos) + "DaoImpl.java";
            dao.add(new File(this.basePath() + File.separator +
                    "dao" + File.separator + daoFileName));
            daoImpl.add(new File(this.basePath() +
                    File.separator + "dao" + File.separator + "impl" +
                    File.separator + daoImplFileName));
            String serviceFileName = "I" + fileName.substring(0, pos) + "Service.java";
            String serviceImplFileName = fileName.substring(0, pos) + "ServiceImpl.java";
            service.add(new File(this.basePath() + "" +
                    File.separator + "service" + File.separator +serviceFileName));
            serviceImpl.add(new File(this.basePath() +
                    File.separator + "service" + File.separator + "impl" +
                    File.separator + serviceImplFileName));
        }
        fileMap.put("dao", dao);
        fileMap.put("daoImpl", daoImpl);
        fileMap.put("service", service);
        fileMap.put("serviceImpl", serviceImpl);
        return fileMap;
    }

    /**
     * 返加文件夹操作权限
     * @param directoryFile
     * @param packageInfo 创建文件夹
     * @return File
     */
    public File packageToFile(String packageInfo) {
        StringBuffer strBuff = new StringBuffer(basePath());
        strBuff.append(File.separator + packageInfo.replace(".", File.separator));
        File file = new File(strBuff.toString());
        file.mkdirs();
        return file;
    }

    /**
     * 基础信息
     * @return String
     */
    public String basePath(){
        int i = this.entityDir.lastIndexOf(File.separator);
        System.out.println("");
        System.out.println(this.entityDir.substring(0, i));
        String basePath = this.entityDir.substring(0, i);
        log.info(basePath);
        return basePath;
    }

    public String javaFileToClassName(String javaFileName) {
        int i = javaFileName.indexOf(".");
        return javaFileName.substring(0, i);
    }

    public String dateToString() {
        SimpleDateFormat simp = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        return simp.format(new Date());
    }

    public String getEntityDir() {
        return entityDir;
    }

    public void setEntityDir(String entityDir) {
        this.entityDir = entityDir;
    }

}

 

 

spring2.5之前片本

package com.annotationtodaotoservice;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

/**
 * @see 生成Spring bean 文件
 * @author liuqing
 */
public class SpringBeanFileImpl extends DaoServiceImpl {

    private String packeInformation;

    private String outFilePath;


    public static void main(String args[]) throws FileNotFoundException {
        SpringBeanFileImpl imp =
                new SpringBeanFileImpl("com.hd.digitalxcampus","f:\\beaninfo");
        imp.setEntityDir("E:\\liuqing\\workspace\\phs\\workspace\\phs\\src\\com\bs\\phs\\domain\\report");
        imp.toSpringBeanFile();
    }

    public SpringBeanFileImpl() {
    }

    public SpringBeanFileImpl(String packeInformation, String outFilePath) {
        this.packeInformation = packeInformation;
        this.outFilePath = outFilePath;
    }

    public void toSpringBeanFile() throws FileNotFoundException {
        System.out.println("---" + this.outFilePath);
        OutputStream outputDao = new FileOutputStream(this.outFilePath + File.separator + "spring-dao.xml");
        OutputStream outputService = new FileOutputStream(this.outFilePath + File.separator + "spring-service.xml");
        PrintWriter outDao = new PrintWriter(outputDao);
        PrintWriter outService = new PrintWriter(outputService);
        for (String clazzName:this.getClazzName()) {
            bean(clazzName,outDao,outService);
        }
        if (outputDao != null) {
            try {
                outputDao.close();
            }
            catch (IOException ex) {
            }
        }
        if (outputService != null) {
            try {
                outputService.close();
            }
            catch (IOException ex) {
            }
        }

    }

    public List<String> getClazzName() throws FileNotFoundException {
        List<String> classNames = new ArrayList<String>();
        File entityFiles[] = this.entityFileDir();
        for (File en:entityFiles) {
            classNames.add(this.javaFileToClassName(en.getName()));
        }
        return classNames;
    }

    public void bean(String clazzName,PrintWriter outDao
            ,PrintWriter serviceDao) {
        this.toIdInfo(clazzName, 1);
        outDao.println("<bean id=\"" + this.firstLower(clazzName) + "Dao" +
                "\" parent=\"adminInfoDao\" class=\"" + this.daoClassName(clazzName) +
                "\"> ");
        outDao.println("</bean>");

        serviceDao.println("<bean id=\"" + this.firstLower(clazzName) + "Service" +
                "\" class=\"" + this.serviceClassName(clazzName) +
                "\"> ");
//        <property name="baseDao" ref="foodTypeDao" />
        serviceDao.println("    <property name=\"baseDao\" ref=\"" +
                this.firstLower(clazzName) + "Dao" +
                "\" />");
        serviceDao.println("</bean>");
        outDao.flush();
        serviceDao.flush();
    }
    /**
     * 
     * @param clazzName
     * @param type 1: dao; 2: service;
     * @return
     */
    public String toIdInfo(String clazzName,int type) {
        if (type == 1) {
            return this.packeInformation + ".dao.impl." + clazzName + "DaoImpl";
        }
        else if (type == 2) {
            return this.packeInformation + ".service.impl." + clazzName + "ServiceImpl";
        }
        else {
            return null;
        }
    }
    /**
     *
     * @param clazzName
     * @return
     */
    public String daoClassName(String clazzName) {
        return this.toIdInfo(clazzName, 1);
    }

    /**
     * 
     * @param clazzName
     * @return
     */
    public String serviceClassName(String clazzName) {
         return this.toIdInfo(clazzName, 2);
    }

    /**
     * 
     * @param clazzName
     * @return String
     */
    public String firstLower(String clazzName) {
        char ch[] = clazzName.toCharArray();
        if (ch[0] <= ((char)'z') && ch[0] >= ((char)'A')) {
            ch[0] = (char)(ch[0] + 32);
        }
        return new String(ch);
    }

    public String getPackeInformation() {
        return packeInformation;
    }

    public void setPackeInformation(String packeInformation) {
        this.packeInformation = packeInformation;
    }

    public String getOutFilePath() {
        return outFilePath;
    }

    public void setOutFilePath(String outFilePath) {
        this.outFilePath = outFilePath;
    }

}

 

 

分享到:
评论

相关推荐

    Eclipse 插件 生成dao层实现类 和服务层 action等

    生成struts2 dwr spring 配置文件和数据操作类(com.comm 中BaseDao) idao层 dao层的实现类 Service 层和IService层 总的情况为 src 下有 com.comm BaseDao com.idao pojo所在的类的接口 com.daoimlp pojo所在...

    Spring-generator一键生成数据库文件

    Spring-generator 是基于 javafx8 开发的图形界面 Spring 代码生成器,使用 Apache FreeMarker 作为代码文件的模板,用户可以一键将数据库中的表生成为任意风格的 .java 代码文件(比如经典的三层模型)。 Spring-...

    JavaBean实体类 配置文件 代码一键自动生成工具

    代码一键自动生成工具 可生成Action、JavaBean实体类、Dao及实现类、service及实现类、spring.xml、struts.xml、mybatis.xml *该工具目前支持3种数据源的生成方式,分别是:JDBC、.table、PDM *JDBC:选择JDBC是只...

    Java代码生成工具新版

    生成Hibernate POJO类,Dao类,Service类,Action类。 生成保存,删除,修改,批量保存,批量修改,批量删除,按条件查询,分页查询等功能。 生成各大主流框架配置文件及JSP页面。 一键生成整个项目,加入Jar包部署...

    spring boot+mybatis整合

    7、生产Dao层和entity类 8、建立controller层类 9、建立service层类 10、启动之后结果展示 --------------------- 作者:silentwolfyh 来源:CSDN 原文:...

    Java代码生成工具(傻瓜式操作无需教程的代码生成工具) v2.0.zip

    生成hibernate pojo类,dao类,service类,action类。  生成保存,删除,修改,批量保存,批量修改,批量删除,按条件查询,分页查询等功能。  生成各大主流框架配置文件及jsp页面。  一键生成整个项目,加入...

    Spring集成MyBatis.docx

    七、创建Service接口和实现类,属性是dao 八、创建spring的配置文件 九、创建测试类 十、总结 将 MyBatis与 Spring 进行整合,主要解决的问题就是将 SqlSessionFactory 对象交由 Spring来管理。所以,该整合...

    SSM代码生成工具/改进版Mybatis代码生成工具

    4.service的实现类中,新增和更新操作已实现字符串解析功能.此类尤其建议使用超类(basic包下)自适应获取数据库的分页方法. 5.controller: 包含add,update,delete,info,list方法,包含try-catch与返回值. 注:超类使用...

    自动代码生成

    只需要配置两个文件即可运行,①数据库连接文件 ②生成文件的路径和包名等的文件 代码中尽量减少使用了第三方的 jar 包,基本上是愿生的代码,避免朋友们因为jar包发愁,也没有使用maven管理,就是一个java项目,...

    ssh2(struts2+spring2.5+hibernate3.3)自动生成模版

    GeneratorMain.java(该类用来传入一个参数:"表名(数据库表)",然后就会生成想要生成的模版),Generator.java(该类实现想要定制哪些模版文件来进行生成,生成后的文件存放在哪里),generator.properties(配置自己的...

    SSH代码生成工具 SSH代码生成器

    Service --&gt; Service接口定义类 DAO --&gt; DAO接口定义类 DAOImpl --&gt; DAO接口Implements实现类 程序配置 --&gt; web.xml 验证框架--&gt; bean-validation.xml (实体验证)、SaveAction-validation.xml (保存验证)、...

    ssh代码生成器轻松、快捷

    Service --&gt; Service接口定义类 DAO --&gt; DAO接口定义类 DAOImpl --&gt; DAO接口Implements实现类 程序配置 --&gt; web.xml 验证框架--&gt; bean-validation.xml (实体验证)、SaveAction-validation.xml (保存验证)、Update...

    JAVA源码 代码一键自动生成工具

    代码一键自动生成工具 可生成Action、JavaBean实体类、Dao及实现类、service及实现类、spring.xml、struts.xml、mybatis.xml *该工具目前支持3种数据源的生成方式,分别是:JDBC、.table、PDM *JDBC:选择JDBC是只...

    JAVA代码生成,支持模板自定义,完美运行

    2.ssm模板实现:pojo,dao,daoimpl,service,serviceimpl,controller,各mapper.xml 代码自动生成, 3.配置文件自动生(含:spring,springMVC,mybatis,web.xml); 代码完美运行. 使用: 1.配置generator.xml(key):...

    Spring中文帮助文档

    3.10. 以J2EE RAR文件的形式部署Spring ApplicationContext 3.11. 基于注解(Annotation-based)的配置 3.11.1. @Autowired 3.11.2. 基于注解的自动连接微调 3.11.3. CustomAutowireConfigurer 3.11.4. @...

    java大作业基于SSH框架的学生成绩管理系统源码.zip

    5、 生成Hibernate所需的POJO类和映射文件 6、 开发DAO层 ​ (1) 新建DAO层接口。 ​ (2) 新建DAO层实现类(该类要实现DAO层接口,继承HibernateDaoSupport类)。 ​ (3) 在Spring配置文件中增加该DAO层...

    AutoCode代码生成器(SSH版)

    Service --&gt; Service接口定义类 DAO --&gt; DAO接口定义类 DAOImpl --&gt; DAO接口Implements实现类 程序配置 --&gt; web.xml 验证框架--&gt; bean-validation.xml (实体验证)、SaveAction-validation.xml (保存验证)、...

    Spring API

    2. Spring 2.0和 2.5的新特性 2.1. 简介 2.2. 控制反转(IoC)容器 2.2.1. 新的bean作用域 2.2.2. 更简单的XML配置 2.2.3. 可扩展的XML编写 2.2.4. Annotation(注解)驱动配置 2.2.5. 在classpath中自动搜索组件...

    springmvc mybatis 自动生成

    controller,dao,mapper,service,同时包含了常用的功能块比如分页等。在webRoot目录下会生成back文件夹生成的相应的jsp文件会在此文件夹下。(注意:一定要有webRoot文件夹切记不可用WebContent代替) 生成之后...

    AutoCode代码生成器【SSH版】

    Service --&gt; Service接口定义类 DAO --&gt; DAO接口定义类 DAOImpl --&gt; DAO接口Implements实现类 程序配置 --&gt; web.xml 验证框架--&gt; bean-validation.xml (实体验证)、SaveAction-validation.xml (保存验 证)、...

Global site tag (gtag.js) - Google Analytics