必威体育Betway必威体育官网
当前位置:首页 > IT技术

代码生成器

时间:2019-08-01 18:39:59来源:IT技术作者:seo实验室小编阅读:71次「手机版」
 

代码生成器

笔者由于觉得很多东西都用工具可以做到很便利 公司由于换成Springboot和用Springdata JPA开发 所以本人觉得什么都要手写效率不高(觉得超级烦好不好)故使用freemaker生成了一些通用的代码

这里生成用到了两种方式 一种用模板 一种直接在内存生成(字符串拼接) 

这里用maven来构建项目 后面会等基本功能完善好会扩展到项目里面 这里只能当初单独的生成工程来使用了

https://gitee.com/TangHuihuang/process  源码放在码云

大概思路在下面

1. jdbc连接数据库 循环查找出表

2. 取得表的列 加入colnames

3. 取得表的列名类型

4. 在内存生成bean java文件和Vo的java文件

5.生成service和dao和controller 用模板生成

6.编译java文件 获得class对象 

7.生成页面 完成

先上效果图

话不多话 直接撸码

工程结构

annotation包:

首先是自定义注解

package annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.runtime)  
@Target(ElementType.field)//
public @interface Caption {
	
	String value() default "";
}

这是用来生成字段对应的文字跟数据库的字段注释对应 后面用来生成jsp页面的label标签的值

javaclass包下 

:自定义classLoader 由于我要寻找自己的路径的class 所以继承了ClassLoader 来装饰 这里参考某个博客的写法 但是当时没有记下来~

package javaclass;

import java.io.IOException;

import javax.tools.*;


public class ClassFileManager extends ForwardingJavaFileManager {

    private JavaClassFileObject classFileObject;
    /**
     * Creates a new instance of ForwardingJavaFileManager.
     *
     * @param fileManager delegate to this file manager
     */
    public ClassFileManager(JavaFileManager fileManager) {
        super(fileManager);
    }

    /**
     * Gets a JavaFileObject file object for output
     * representing the specified class of the specified kind in the given location.
     */
    @Override
    public JavaFileObject getJavaFileForOutput(Location location, String className, JavaFileObject.Kind kind, 
    FileObject sibling) throws IOException {
        classFileObject = new JavaClassFileObject(className, kind);
        return classFileObject;
    }

    @Override
    //获得一个定制ClassLoader,返回我们保存在内存的类
    public ClassLoader getClassLoader(Location location) {
        return new ClassLoader() {
            @Override
            protected Class<?> findClass(String name) throws ClassnotfoundException {
                byte[] classBytes = classFileObject.getClassBytes();
                return super.defineClass(name, classBytes, 0, classBytes.length);
            }
        };
    }
}
package javaclass;

import java.io.ByteArrayoutputstream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;
import java.nio.file.WatchEvent.Kind;
import javax.tools.*;

public class JavaClassFileObject extends SimpleJavaFileObject {
    //用于存储class字节
    ByteArrayOutputStream outputStream;

    public JavaClassFileObject(String className, Kind kind) {
        super(URI.create("string:///" + className.replace('.', '/') + kind.extension), kind);
        outputStream = new ByteArrayOutputStream();
    }

    @Override
    public OutputStream openOutputStream() throws IOException {
        return outputStream;
    }

    public byte[] getClassBytes() {
        return outputStream.toByteArray();
    }
}
package javaclass;
import java.net.URI;

import javax.tools.*;

/**
 * A file object used to represent source coming from a string.
*/
public class JavaSourceFromString extends SimpleJavaFileObject {
	/**
	 * The source code of this "file".
	 */
	final String code;
	/**
	 * Constructs a new JavaSourceFromString.
	 * @param name the name of the compilation unit represented by this file object
	 * @param code the source code for the compilation unit represented by this file object
	 */
	public JavaSourceFromString(String name, String code) {
	    super(URI.create("string:///" + name.replace('.','/') + Kind.SOURCE.extension), Kind.SOURCE);
	    this.code = code;
	}
	
	@Override
	public Charsequence getCharcontent(boolean ignoreEncodingERRORs) {
	    return code;
	}
}
package javaclass;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.fileinputstream;
import java.io.IOException;

public class MyClassLoader extends ClassLoader {
	
	  private String mLibPath;
	  
	  public MyClassLoader(String path) {
	        // TODO Auto-generated constructor stub
	        mLibPath = path;
	    }
	  
	  @Override
	    protected Class<?> findClass(String name) throws ClassNotFoundException {
	        // TODO Auto-generated method stub

	        String fileName = getFileName(name);

	        File file = new File(mLibPath,fileName);

	        try {
	            FileInputStream is = new FileInputStream(file);

	            ByteArrayOutputStream bos = new ByteArrayOutputStream();
	            int len = 0;
	            try {
	                while ((len = is.read()) != -1) {
	                    bos.write(len);
	                }
	            } catch (IOException e) {
	                e.printstacktrace();
	            }

	            byte[] data = bos.toByteArray();
	            is.close();
	            bos.close();

	            return defineClass(name,data,0,data.length);

	        } catch (IOException e) {
	            // TODO Auto-generated catch block
	            e.printStackTrace();
	        }

	        return super.findClass(name);
	    }

	    //获取要加载 的class文件名
	    private String getFileName(String name) {
	        // TODO Auto-generated method stub
	        int index = name.lastindexof('.');
	        
	        if(index == -1){ 
	        	System.out.println(name);
	            return name+".class";
	        }else{
	        	System.out.println(name);
	            return name.substring(index+1)+".class";
	        }
	    }

}

说下util包:用到的

jdbc数据库链接

package util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Preparedstatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DB {
	
	public static String  path = "";   
    public static String url = "";  
    public static String driver = "";  
    public static String user = "";  
    public static String password = "";  
    static{
    	 path = PathUitl.getFilePath("all.properties");
    	 if(path==null){
    		 throw new NullPointerException("获取配置文件路径错误!找不到配置");
    	 }
    	 String jdbcPropertiesPath = PathUitl.getClasspath()+PropertyUtil.getPro(path, "jdbc.url");
    	
    	 driver = PropertyUtil.getPro(jdbcPropertiesPath, "jdbc.classname");
    	 url = PropertyUtil.getPro(jdbcPropertiesPath, "jdbc.url");
    	 user =  PropertyUtil.getPro(jdbcPropertiesPath, "jdbc.username");
    	 password = PropertyUtil.getPro(jdbcPropertiesPath, "jdbc.password");
    }
    	

	public static PreparedStatement getPStmt(Connection connection,String sql) throws SQLException{
		/*Statement st=connection.createStatement();
		ResultSet rs=st.executequery(sql);*/
		PreparedStatement pst=connection.preparestatement(sql);
	//	pst.execute();
		return pst;
	}

	public static void close(PreparedStatement pstmt) throws SQLException {
		if(pstmt!=null){
			pstmt.close();
		}
		
	}

	public static Connection getConn() throws SQLException {
		Connection conn=DriverManager.getConnection(url, user, password);
		return conn;
	}

	public static void close(Connection conn) {
		if(conn!=null){
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}
	
}
package util;

import java.io.File;

public class FileUtil {

	public static boolean checkDir(File dir){
		  return dir.exists()&&dir.isDirectory();
	}
}
package util;

import java.io.File;

/**
 * 用separator()方法代替路径中的”/”或”\” 。
 * 用pathSeptarator()方法代替路径中的 ” : ” 或 ” ;” 。
 * @author kaizen
 *
 */
public class PathUitl {

	 	/**
	   * 
	   * @return 获取绝对路径
	   * 然后在项目路径后面拼接"properties/sysConfig.properties"; 
	   */
	 public static String getClasspath()
	  {
	    String path = (String.valueOf(Thread.currentThread().getcontextClassLoader().getResource(""))).replaceAll("file:/", "").replaceAll("%20", " ").trim();
	    if (path.indexOf(":") != 1) {
	      path = File.separator + path;
	    }
	    return path;
	  }
	 
	  public static String getPorjectPath()
	  {
	    String nowpath = "";
	    nowpath = system.getproperty("user.dir") + "/";
	    return nowpath;
	  }
	  
	  public static String getFilePath(String fileName)
	  {
	    String nowpath = "";
	    nowpath =ClassLoader.getSystemResource(fileName).toString().replaceAll("file:/", "");
	    return nowpath;
	  }
	  
	 
	  public static void main(String[] args) {
			System.out.println( PathUitl.getFilePath("jdbc.properties"));//D:/Eclipse_workspace/test/target/classes/jdbc.properties
	    	//String jdbcPropertiesPath = PathUitl.getClasspath()+PropertyUtil.getPro(path, "jdbc.url");

		}
	  
}
package util;

import java.io.FileInputStream;
import java.io.filenotfoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

public class PropertyUtil {
	private static Properties prop;  
    
    public static void load(String path){  
        //这里的path是项目文件的绝对路径  
        //先获取项目绝对路径:Thread.currentThread().getContextClassLoader().getResource("").getPath();  
        //然后在项目路径后面拼接"properties/sysConfig.properties";  
        prop= new Properties();// 属性集合对象     
        FileInputStream fis = null;    
        try {    
            System.out.println(path);  
            fis = new FileInputStream(path);  
            prop.load(fis);  
        } catch (FileNotFoundException e) {    
            e.printStackTrace();    
        } catch (IOException e) {    
            e.printStackTrace();    
        }finally{
        	try {
        		if(null!=fis){
        			fis.close();
        		}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}// 关闭流    
        }   
    }  
      
    //参数为要修改的文件路径  以及要修改的属性名和属性值    
    public static Boolean updatePro(String path,String key,String value){  
        if(prop==null){  
            load(path);  
            System.out.println("修改前重新加载一遍");  
        }  
        System.out.println("获取添加或修改前的属性值:"+key+"=" + prop.getProperty(key));  
        prop.setProperty(key, value);    
        FileOutputStream fos = null;
        // 文件输出流     
        try {    
        	fos = new FileOutputStream(path);     
            // 将Properties集合保存到流中     
            prop.store(fos, "Copyright (c) Boxcode Studio");     
            
        } catch (FileNotFoundException e) {    
            // TODO Auto-generated catch block    
            e.printStackTrace();    
            return false;    
        } catch (IOException e) {    
            // TODO Auto-generated catch block    
            e.printStackTrace();    
            return false;    
        }finally{
        	try {
        		if(null!=fos){
        			fos.close();
        		}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}// 关闭流     
        }   
        System.out.println("获取添加或修改后的属性值:"+key+"=" + prop.getProperty(key));  
        return true;    
    }    
      
  //参数为要修改的文件路径  以及要修改的属性名和属性值    
    public static String getPro(String path,String key){    
        if(prop==null){  
            load(path);  
            System.out.println("重新加载一遍");  
        }  
        FileInputStream fis = null;    
        try {    
            fis = new FileInputStream(path);    
            prop.load(fis);// 将属性文件流装载到Properties对象中     
        } catch (FileNotFoundException e) {    
            e.printStackTrace();    
        } catch (IOException e) {    
            e.printStackTrace();    
        }finally{
        	try {
        		if(null!=fis){
        			fis.close();
        		}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}// 关闭流    
        }      
        System.out.println("查询到的"+key+"的值:"+prop.getProperty(key));  
        return prop.getProperty(key);    
    }    
    
    public static void main(String[] args) {
    	String path = PathUitl.getFilePath("all.properties");
    	String vaule = PropertyUtil.getPro(path, "jdbc.url");
    	System.out.println(vaule);// /jdbc.properties
	}
}
package util;

public class StringUtil {

	
	 /**
     * 功能:将输入字符串的首字母改成大写
     * 
     * @param str
     * @return
     */
    public static String initcap(String str) {
        char[] ch = str.toCharArray();
        if (ch[0] >= 'a' && ch[0] <= 'z') {
            ch[0] = (char) (ch[0] - 32);
        }
        return new String(ch);
    }
    /**
     * 功能:将输入字符串的首字母改成小写
     * 
     * @param str
     * @return
     */
    public static String initLowerCase(String str) {
        char[] ch = str.toCharArray();
        if (ch[0] >= 'A' && ch[0] <= 'Z') {
            ch[0] = (char) (ch[0] + 32);
        }
        return new String(ch);
    }
    /**
     *  字符转换成大写的字符String
     * @param ch
     * @return
     */
    public static String initChar(char ch){
    	 if (ch >= 'a' && ch <= 'z') {
             ch = (char) (ch- 32);
         }
         return String.valueOf(ch);
    }
    
    public static String initCapAndUnderline(String str){
    	str = str.substring(0, 1).toUpperCase()+str.substring(1);
    	
    	int i = str.indexOf("_");
    	while(i!=(-1)){
    			if(str.length()-1>i){
    				str = str.substring(0,i)+initChar(str.charAt(i+1))+str.substring(i+2);
    			}else{
    				str = str.substring(0,i);
    			}
    			i = str.indexOf("_");
    	}
    	
    	return str;
    	
    }
    
    public static String initUnderline(String str){
    	int i = str.indexOf("_");
    	while(i!=(-1)){
    			if(str.length()-1>i){
    				str = str.substring(0,i)+initChar(str.charAt(i+1))+str.substring(i+2);
    			}else{
    				str = str.substring(0,i);
    			}
    			i = str.indexOf("_");
    	}
    	
    	return str;
    	
    }
}

test包下:

生成类在这里

package test;

import java.io.File;
import java.io.FileWriter;
import java.io.printwriter;
import java.net.URL;
import java.net.URLClassLoader;
import java.sql.Connection;
import java.sql.databasemetadata;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import javax.tools.JavaCompiler;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;

import javaclass.MyClassLoader;
import util.DB;
import util.FileUtil;
import util.PathUitl;
import util.PropertyUtil;
import util.StringUtil;

public class ReverseEntity2 {
	

    private static String packageOutPath;// 指定实体生成所在包的路径
    private static String authorName;// 作者名字
    private static String tablename;// 表名
    private static String databasename;// 数据库名
    private List<String> tablenames;// 拿到对应数据库中所有的实体类(实体类需要与其他表明做区分)
    private List<String> colnames; // 列名集合
    private List<String> coltypes; // 列名类型集合
    private List<String> colAnnotation;//注释
    
    public static final String ENTER = "\n";//换行

    
    
    private boolean f_util = false; // 是否需要导入包java.util.*
    private boolean f_sql = false; // 是否需要导入包java.sql.*
    
	public static String  path = "";   //存放配置文件的路径的配置文件
	private static String jdbcPropertiesPath = "";//获取jdbc的配置文件路径

    static{
    	 path = PathUitl.getFilePath("all.properties");
    	 if(path==null){
    		 throw new NullPointerException("获取配置文件路径错误!找不到配置");
    	 }
    	 jdbcPropertiesPath = PathUitl.getClasspath()+PropertyUtil.getPro(path, "jdbc.url");
    	 databasename = PropertyUtil.getPro(jdbcPropertiesPath, "databasename");
    	 packageOutPath = PropertyUtil.getPro(jdbcPropertiesPath, "packageOutPath");
    	 tablename =  PropertyUtil.getPro(jdbcPropertiesPath, "tablename");
    	 authorName = PropertyUtil.getPro(jdbcPropertiesPath, "authorName");
    }
    	 
    	 
    
    // 创建多个实体类
    private void genEntity(List<String> tablenames, Connection conn) {
        // 使用第归生成文件
        for (String tablename : tablenames) {
            this.genEntity(tablename, conn);
        }
    }

    // 创建单个实体类
    private void genEntity(String tablename, Connection conn) {
        String sql = "select * from " + tablename;
        
        DatabaseMetaData dbmd = null;  
        try {
	         dbmd = conn.getMetaData();
	         ResultSet resultSet = dbmd.getTables(null, "%", tablename, new String[] { "TABLE" });  
	        
	         while (resultSet.next()) {  
	        	 
	        	 String table=resultSet.getString("TABLE_NAME");  
                 System.out.println(table);
                 
                 if(table.equals(tablename))
                 {
                	 ResultSet rs = conn.getMetaData().getColumns(null,  conn.getMetaData().getUserName(), tablename, "%");  
                	 if(rs!=null)
                	 {
                		 colnames = new ArrayList<String>();
         	            
                		 colTypes = new ArrayList<String>();
         	            
                		 colAnnotation = new ArrayList<String>();
                		 
                		 while(rs.next())
                		 {  
                			 colnames.add(rs.getString("COLUMN_NAME"));
                			 colTypes.add(rs.getString("TYPE_NAME"));
                			 if(null!=rs.getString("REMARKS")){
                				 colAnnotation.add(rs.getString("REMARKS"));
                			 }else{
                				 colAnnotation.add(rs.getString(" "));
                			 }
                		 }
                	 }
                	 
                 }
	        	 
	         }
           
            if (colTypes.contains("datetime")) {
                f_util = true;
            }
            if (colTypes.contains("image")
                    || colTypes.contains("text")) {
                f_sql = true;
            }
            System.out.println(colnames);
            System.out.println(colTypes);
        } catch (SQLException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } finally {
        }
        
        // 在内存中生成代码
        String entityContent = parse(tablename);
        String voContent = parseVo(tablename);

        // 写入到文件中
        try {
           // File directory = new File("");
           // String outputPath = directory.getabsolutePath() + "/src/"
                   // + this.packageOutPath.replace(".",File.separator) + StringUtil.initCapAndUnderline(tablename) +File.separator;
            
            String entityOutputPath = PathUitl.getClasspath()
                    /*+ this.packageOutPath.replace(".",File.separator) +File.separator*/
                    +  StringUtil.initCapAndUnderline(tablename) +File.separator;
            
            // 检测路径是否存在,不存在就创建路径
            File entityPath = new File(entityOutputPath);
            
            if(!FileUtil.checkDir(entityPath)){
            	entityPath.mkdirs();
            }
            // 创建文件
            String entityOutputPathJava = entityOutputPath+StringUtil.initCapAndUnderline(tablename) + ".java";
            String voOutputPathJava = entityOutputPath+StringUtil.initCapAndUnderline(tablename) + "Vo.java";
             System.out.println(entityOutputPathJava);
            File entityFile = new File(entityOutputPathJava);
            File voFile = new File(voOutputPathJava);

            
            
            if (!entityFile.exists()) {
            	entityFile.createnewfile();
            }
            if (!voFile.exists()) {
            	voFile.createNewFile();
            }
            
            // 写出到硬盘
            FileWriter fw = new FileWriter(entityFile);
            PrintWriter pw = new PrintWriter(fw);
            
            FileWriter vofw = new FileWriter(voFile);
            PrintWriter vopw = new PrintWriter(vofw);

         
            pw.println(entityContent);
            pw.flush();
            pw.close();
            vopw.println(voContent);
            vopw.flush();
            vopw.close();
            
            //编译
            JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
            StandardJavaFileManager fileManager = compiler.getStandardFileManager(null,null, null);
            Iterable fileObject = fileManager.getJavaFileObjects(entityOutputPathJava);
            JavaCompiler.CompilationTask task = compiler.getTask(
                    null, fileManager, null, null, null, fileObject);
            task.call();
            fileManager.close();
            
            //获得实例
            MyClassLoader myClassLoader = new MyClassLoader(entityOutputPath);
            //URLClassLoader classLoader = new URLClassLoader(new URL[]{new URL("file:" +  PathUitl.getClasspath()+ this.packageOutPath.replace(".",File.separator) +File.separator+ initCapAndUnderline(tablename) +File.separator)});
           //这里与Bean  packger的路径一样
            Class beanClass = myClassLoader.loadClass(this.packageOutPath+".bean."+StringUtil.initCapAndUnderline(tablename));
            Object obj = beanClass.newInstance();
            
            
          /*  SimpleJavaFileObject fileObject = new JavaSourceFromString(initCapAndUnderline(tablename),entityContent);
            JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
            JavaFileManager fileManager = new ClassFileManager(compiler.getStandardFileManager(null, null, null));
            JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, null, null, null, Arrays.asList(fileObject));
            task.call();
            
            //获得ClassLoader,加载class文件
            ClassLoader classLoader = fileManager.getClassLoader(null);
            Class beanClass = classLoader.loadClass(initCapAndUnderline(tablename));*/
            
            //生成dao,Service,vo
            Process.processDao(this.packageOutPath,StringUtil.initCapAndUnderline(tablename),entityOutputPath);
            Process.processService(this.packageOutPath,StringUtil.initCapAndUnderline(tablename),entityOutputPath);
            Process.processMService(this.packageOutPath,StringUtil.initCapAndUnderline(tablename), entityOutputPath, obj);
            Process.processServiceImpl(this.packageOutPath,StringUtil.initCapAndUnderline(tablename),entityOutputPath);
            Process.processController(this.packageOutPath,StringUtil.initCapAndUnderline(tablename),entityOutputPath);
            Process.processMController(this.packageOutPath,StringUtil.initCapAndUnderline(tablename),entityOutputPath);

            
            //生成jsp页面
            Process.processJsp(obj,entityOutputPath);
            beanClass=null;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String parseVo(String tablename2) {
    	 StringBuffer sb = new StringBuffer();
         sb.APPend("package " + this.packageOutPath + ".vo;\r\n");
         // 判断是否导入工具包
         if (f_util) {
             sb.append("import java.util.Date;\r\n");
         }
         if (f_sql) {
             sb.append("import java.sql.*;\r\n");
         }
         sb.append("import annotation.*;\r\n");
        
         sb.append("\r\n");
         // 注释部分
         sb.append("   /**\r\n");
         sb.append("    * " + tablename + " VO类\r\n");
         sb.append("    * " + new Date() + " " + this.authorName + "\r\n");
         sb.append("    */ \r\n");
         // 实体部分 class
         sb.append("\r\n\r\npublic class " + StringUtil.initCapAndUnderline(tablename) + "Vo {\r\n");
         sb.append(ENTER);
         processAllAttrsWithOutAnno(sb);// 属性
         processAllMethod(sb);// get set方法
         sb.append("}\r\n");

         
         return sb.toString();
	}

	private void getAllEntityTable(Connection conn, List<String> tablenames) {
        ResultSet rs = null;
        try {
            DatabaseMetaData dmd = (DatabaseMetaData) conn.getMetaData();
            /*
             * TABLE_CAT String => 表类别(可为 null) 
             * TABLE_SCHEM String => 表模式(可为null) 
             * TABLE_NAME String => 表名称 
             * TABLE_TYPE String => 表类型
             */
            rs = dmd.getTables(null, null, "%", null);
            while (rs.next()) {
                tablenames.add(rs.getString("TABLE_NAME"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 
     * @param tablename
     * @return
     */
    private String parse(String tablename) {
        StringBuffer sb = new StringBuffer();
        sb.append("package " + this.packageOutPath + ".bean;\r\n");
        // 判断是否导入工具包
        if (f_util) {
            sb.append("import java.util.Date;\r\n");
        }
        if (f_sql) {
            sb.append("import java.sql.*;\r\n");
        }
        sb.append("import annotation.*;\r\n");
        sb.append("import javax.persistence.Column;\r\n");
        sb.append("import javax.persistence.Entity;\r\n");
        sb.append("import javax.persistence.GeneratedValue;\r\n");
        sb.append("import javax.persistence.Id;\r\n");
        sb.append("import javax.persistence.Table;\r\n");
       
        sb.append("\r\n");
        // 注释部分
        sb.append("   /**\r\n");
        sb.append("    * " + tablename + " 实体类\r\n");
        sb.append("    * " + new Date() + " " + this.authorName + "\r\n");
        sb.append("    */ \r\n");
        // 实体部分 class
        sb.append("\r\n@Table(name = \""+tablename+"\")\r\n");
        sb.append("\r\n\r\npublic class " + StringUtil.initCapAndUnderline(tablename) + "{\r\n");
        sb.append(ENTER);
        processAllAttrs(sb);// 属性
        processAllMethod(sb);// get set方法
        sb.append("}\r\n");

        
        return sb.toString();
    }

    /**
     * 功能:生成所有属性(含有注解)
     * 
     * @param sb
     */
    private void processAllAttrs(StringBuffer sb) {

        for (int i = 0; i < colnames.size(); i++) {
        	if(null!=colAnnotation.get(i)&&!colAnnotation.get(i).equals("")){
        		
        		sb.append("\t@Caption(\""+colAnnotation.get(i)+"\")\n");
        	}
        	if(colnames.get(i).equals("seq_id")){
    			sb.append("\t@Id\n");
    			sb.append("\t@GeneratedValue\n");
    			sb.append("\t@Column(name = \""+colnames.get(i)+"\",unique=true,nullable=false)\n");
    		}else{
    			sb.append("\t@Column(name = \""+colnames.get(i)+"\")\n");
    		}
            sb.append("\tprivate " + sqlType2JavaType(colTypes.get(i)) + " "
                    + StringUtil.initUnderline(colnames.get(i)) + ";\r\n");
            sb.append("\n");
        }
        sb.append("\n");

    }
    
    /**
     * 功能:生成所有属性(无注解)
     * 
     * @param sb
     */
    private void processAllAttrsWithOutAnno(StringBuffer sb) {

        for (int i = 0; i < colnames.size(); i++) {
        	if(null!=colAnnotation.get(i)&&!colAnnotation.get(i).equals("")){
        		
        		sb.append("\t@Caption(\""+colAnnotation.get(i)+"\")\n");
        	}
            sb.append("\tprivate " + sqlType2JavaType(colTypes.get(i)) + " "
                    + StringUtil.initUnderline(colnames.get(i)) + ";\r\n");
            sb.append("\n");
        }
        sb.append("\n");

    }

    /**
     * 功能:生成所有方法
     * 
     * @param sb
     */
    private void processAllMethod(StringBuffer sb) {

        for (int i = 0; i < colnames.size(); i++) {
            sb.append("\tpublic void set" + StringUtil.initCapAndUnderline(colnames.get(i)) + "("
                    + sqlType2JavaType(colTypes.get(i)) + " " + StringUtil.initUnderline(colnames.get(i))
                    + "){\r\n");
            sb.append("\t\tthis." + StringUtil.initUnderline(colnames.get(i)) + "=" + StringUtil.initUnderline(colnames.get(i))
                    + ";\r\n");
            sb.append("\t}\r\n");
            sb.append("\tpublic " + sqlType2JavaType(colTypes.get(i)) + " get"
                    + StringUtil.initCapAndUnderline(colnames.get(i)) + "(){\r\n");
            sb.append("\t\treturn " + StringUtil.initUnderline(colnames.get(i)) + ";\r\n");
            sb.append("\t}\r\n");
        }

    }

   
    
    

    /**
     * 功能:获得列的数据类型
     * 
     * @param sqlType
     * @return
     */
    private String sqlType2JavaType(String sqlType) {

        if (sqlType.equalsignorecase("bit")) {
            return "Boolean";
        } else if (sqlType.equalsIgnoreCase("tinyint")) {
            return "Byte";
        } else if (sqlType.equalsIgnoreCase("smallint")) {
            return "Short";
        } else if (sqlType.equalsIgnoreCase("int")) {
            return "integer";
        } else if (sqlType.equalsIgnoreCase("bigint")) {
            return "Long";
        } else if (sqlType.equalsIgnoreCase("float")) {
            return "Float";
        } else if (sqlType.equalsIgnoreCase("decimal")
                || sqlType.equalsIgnoreCase("numeric")
                || sqlType.equalsIgnoreCase("real")
                || sqlType.equalsIgnoreCase("money")
                || sqlType.equalsIgnoreCase("smallmoney")) {
            return "Double";
        } else if (sqlType.equalsIgnoreCase("varchar")
                || sqlType.equalsIgnoreCase("char")
                || sqlType.equalsIgnoreCase("nvarchar")
                || sqlType.equalsIgnoreCase("nchar")
                || sqlType.equalsIgnoreCase("text")) {
            return "String";
        } else if (sqlType.equalsIgnoreCase("datetime")) {
            return "Date";
        } else if (sqlType.equalsIgnoreCase("image")||
        		sqlType.equalsIgnoreCase("blob")||sqlType.equalsIgnoreCase("binary")) {
            return "byte[]";
        }

        return null;
    }

    /**
     * 出口 TODO
     * 
     * @param args
     */
    public static void main(String[] args) {
    	//String a ="a_a_b_v_";
    	//System.out.println("this is "+StringUtil.initCapAndUnderline(a));
        new ReverseEntity2().start();

    }

    private void start() {
        // 创建连接
        Connection conn = null;
		try {
			conn = DB.getConn();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

        if (databasename != null && !databasename.equals("")
                && tablename != null && !tablename.equals("")) {
            System.out.println("databasename 和 tablename 不能同时存在");
        } else {
            // 如果配置文件中有数据库名字,则可以拿到其中所有的实体类
            if (databasename != null && !databasename.equals("")) {
                // 获取所有实体表名字
                tablenames = new ArrayList<String>();
                getAllEntityTable(conn, tablenames);
                System.out.println("tablenames"+tablenames);
                // 为每个实体表生成实体类
                genEntity(tablenames, conn);
            } else {
            	String[] tablenames = tablename.split(",");
                // 为指定实体表生成实体类
            	for (int i = 0; i < tablenames.length; i++) {
            		genEntity(tablenames[i], conn);
				}
            }

            // 关闭数据库连接
            if (conn != null) {
                DB.close(conn);
            }
        }

    }
}

根据模板生成的细节在这里

package test;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.outputstreamwriter;
import java.io.Writer;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import annotation.Caption;
import freemarker.template.configuration;
import freemarker.template.DefaultObjectwrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import util.PathUitl;
import util.StringUtil;

/**
 * version 1.0
 * @author kaizen
 *
 */
public class Process {
	
	 public static final String prefix="${bean.";
     public static final String suffix="}";
     public static final String jspFilePrefix="/jsp/";
     public static final String ftlFilePrefix="/templetes/";
     public static final String ENTER = "\n";//换行

   //创建一个合适的Configration对象 
     private static Configuration configuration = new Configuration();
     
     static{
    	 
	     try 
	     {
			configuration.setDirectoryForTemplateLoading(new File(PathUitl.getClasspath()));
			configuration.setObjectWrapper(new DefaultObjectWrapper());  
	        configuration.setDefaultEncoding("UTF-8");   //这个一定要设置,不然在生成的页面中 会乱码  
	        
	     } catch (IOException e) {
	    	 // TODO Auto-generated catch block
	    	 e.printStackTrace();
	     }  
        
     }

	
	
	
	public static void processJsp(Object obj,String path){
		if(obj==null||path==null){
			throw new NullPointerException();
		}
		
		 try {  
	            
	            //获取或创建一个模版。  
	            Template template = configuration.getTemplate(jspFilePrefix+"input.jsp");
	            Template template2 = configuration.getTemplate(jspFilePrefix+"list.jsp");
	            Template template3 = configuration.getTemplate(jspFilePrefix+"view.jsp");
	            
	            Map<String, Object> inputParamMap = new HashMap<String, Object>();
	            Map<String, Object> listParamMap = new HashMap<String, Object>();
	           

	            
	            Map<String,Object> captions = new  HashMap<String, Object>();
	            Map<String,Object> listCaptions = new  HashMap<String, Object>();
	            
	            //List fields = new ArrayList();
	            Map<String, Object> fields = new HashMap<String, Object>();
	            
	            Field[] fs =  obj.getClass().getDeclaredFields();
	            for (Field f : fs) {
	            	Caption caption = f.getAnnotation(Caption.class);
	            	if(null!=caption){
	            		if(caption.value().equals("主键")){
		            		inputParamMap.put("seqId", f.getName());
		            		inputParamMap.put("seqIdValue",prefix+f.getName()+suffix);
		            	}else{
		            		captions.put(f.getName(),caption.value());
		            	}
	            		fields.put( f.getName(),prefix+f.getName()+suffix);
	            		listCaptions.put(prefix+f.getName()+suffix, caption.value());
	            	}
				}
	            //Input
	            inputParamMap.put("fields", fields); 
	            inputParamMap.put("captions", captions); 
	            inputParamMap.put("lowercaseBean", StringUtil.initLowerCase(obj.getClass().getSimpleName())); 
	            
	            //List
	            listParamMap.put("listCaptions", listCaptions); 
	            listParamMap.put("page", "page"); 
	            listParamMap.put("fields", fields);  
	            listParamMap.put("pageNumber", "${page.pageNumber}");
	            listParamMap.put("totalPages", "${page.totalPages}");
	            listParamMap.put("search", "search"); 
	            listParamMap.put("lowercaseBean", StringUtil.initLowerCase(obj.getClass().getSimpleName())); 
	            //File file = new File("");
	            //FileOutputStream fos = new FileOutputStream(file);
	            Writer writer  = new OutputStreamWriter(new FileOutputStream(path+StringUtil.initLowerCase(obj.getClass().getSimpleName())+"Input.jsp"),"UTF-8"); 
	            Writer writer2 = new OutputStreamWriter(new FileOutputStream(path+StringUtil.initLowerCase(obj.getClass().getSimpleName())+"List.jsp"),"UTF-8");
	            Writer writer3 = new OutputStreamWriter(new FileOutputStream(path+StringUtil.initLowerCase(obj.getClass().getSimpleName()+"View.jsp")),"UTF-8");

	            template.process(inputParamMap, writer);  
	            template2.process(listParamMap, writer2);
	            template3.process(inputParamMap, writer3); 
	            System.out.println("恭喜,生成成功~~");  
	        } catch (IOException e) {  
	            e.printStackTrace();  
	        } catch (TemplateException e) {  
	            e.printStackTrace();  
	        } 
	}
	
	public static void processDao(String packgerOutPath,String beanName,String path){
		
		//获取或创建一个模版。  
        try 
        {
			Template template = configuration.getTemplate(ftlFilePrefix+"dao.ftl");
           
			Map<String, Object> ParamMap = new HashMap<String, Object>();
            ParamMap.put("packageOutPath", packgerOutPath);
            ParamMap.put("bean", beanName);

            Writer writer  = new OutputStreamWriter(new FileOutputStream(path+"I"+beanName+"Dao.java"),"UTF-8"); 
            template.process(ParamMap, writer);  


			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public static void processService(String packgerOutPath,String beanName,String path){
		//获取或创建一个模版。  
        try 
        {
			Template template = configuration.getTemplate(ftlFilePrefix+"iservice.ftl");
           
			Map<String, Object> ParamMap = new HashMap<String, Object>();
            ParamMap.put("packageOutPath", packgerOutPath);
            ParamMap.put("bean", beanName);

            Writer writer  = new OutputStreamWriter(new FileOutputStream(path+"I"+beanName+"Service.java"),"UTF-8"); 
            template.process(ParamMap, writer);  

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public static void processMService(String packgerOutPath,String beanName,String path,Object obj){
		//获取或创建一个模版。  
        try 
        {
			Template template = configuration.getTemplate(ftlFilePrefix+"mservice.ftl");
			Map<String, Object> ParamMap = new HashMap<String, Object>();
			
			Map<String, Object> fields = new HashMap<String, Object>();
			 Field[] fs =  obj.getClass().getDeclaredFields();
	            for (Field f : fs) {
            		fields.put( f.getName(),"get"+StringUtil.initCapAndUnderline(f.getName()));
				}
            ParamMap.put("packageOutPath", packgerOutPath);
            ParamMap.put("bean", beanName);
            ParamMap.put("fields", fields);
            Writer writer  = new OutputStreamWriter(new FileOutputStream(path+"M"+beanName+"Service.java"),"UTF-8"); 
            template.process(ParamMap, writer);  

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	public static void processServiceImpl(String packgerOutPath,String beanName,String path){
		//获取或创建一个模版。  
        try 
        {
			Template template = configuration.getTemplate(ftlFilePrefix+"service.ftl");
           
			Map<String, Object> ParamMap = new HashMap<String, Object>();
            ParamMap.put("packageOutPath", packgerOutPath);
            ParamMap.put("bean", beanName);

            Writer writer  = new OutputStreamWriter(new FileOutputStream(path+beanName+"Service.java"),"UTF-8"); 
            template.process(ParamMap, writer);  


			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	public static void processController(String packgerOutPath,String beanName,String path){
		
		//获取或创建一个模版。  
        try 
        {
			Template template = configuration.getTemplate(ftlFilePrefix+"controller.ftl");
			Template template2 = configuration.getTemplate(ftlFilePrefix+"url.ftl");
			
			
			Map<String, Object> ParamMap = new HashMap<String, Object>();
            ParamMap.put("packageOutPath", packgerOutPath);
            ParamMap.put("bean", beanName);
            ParamMap.put("lowercaseBean", StringUtil.initLowerCase(beanName));

            Writer writer  = new OutputStreamWriter(new FileOutputStream(path+beanName+"Controller.java"),"UTF-8"); 
            Writer writer1  = new OutputStreamWriter(new FileOutputStream(path+"URL.java"),"UTF-8"); 

            template.process(ParamMap, writer);  
            template2.process(ParamMap, writer1); 
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public static void processMController(String packgerOutPath,String beanName,String path){
		
		//获取或创建一个模版。  
        try 
        {
			Template template = configuration.getTemplate(ftlFilePrefix+"mcontroller.ftl");
			Template template2 = configuration.getTemplate(ftlFilePrefix+"murl.ftl");

			Map<String, Object> ParamMap = new HashMap<String, Object>();
            ParamMap.put("packageOutPath", packgerOutPath);
            ParamMap.put("bean", beanName);
            ParamMap.put("lowercaseBean", StringUtil.initLowerCase(beanName));

            Writer writer  = new OutputStreamWriter(new FileOutputStream(path+"M"+beanName+"Controller.java"),"UTF-8"); 
            Writer writer1  = new OutputStreamWriter(new FileOutputStream(path+"Murl.java"),"UTF-8"); 

            template.process(ParamMap, writer);  
            template2.process(ParamMap, writer1); 

			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	


	/*public static void main(String[] args) {
	  System.out.println(PathUitl.getClasspath());
    System.out.println(PathUitl.getPorjectPath());
    //System.out.println(ClassLoader.getSystemResource("static.html"));
    System.out.println(Bean.class.getSimpleName());//Bean
    System.out.println(Bean.class.getName());//bean.Bean
    
   
    
    Bean bean = new Bean();
	 try {  
          //创建一个合适的Configration对象 
          Configuration configuration = new Configuration();  
          
        
         configuration.setDirectoryForTemplateLoading(new File(PathUitl.getClasspath()));  
          configuration.setObjectWrapper(new DefaultObjectWrapper());  
          configuration.setDefaultEncoding("UTF-8");   //这个一定要设置,不然在生成的页面中 会乱码  
          //获取或创建一个模版。  
          Template template = configuration.getTemplate(filePrefix+"input.jsp");
          Template template2 = configuration.getTemplate(filePrefix+"list.jsp");
          Template template3 = configuration.getTemplate(filePrefix+"view.jsp");
          
          Map<String, Object> inputParamMap = new HashMap<String, Object>();
          Map<String, Object> listParamMap = new HashMap<String, Object>();
         

          
          Map<String,Object> captions = new  HashMap<String, Object>();
          Map<String,Object> listCaptions = new  HashMap<String, Object>();
          
          //List fields = new ArrayList();
          Map<String, Object> fields = new HashMap<String, Object>();
          
          Field[] fs =  bean.getClass().getDeclaredFields();
          for (Field f : fs) {
          	Caption caption = f.getAnnotation(Caption.class);
          	if(caption.value().equals("主键")){
          		inputParamMap.put("seqId", f.getName());
          		inputParamMap.put("seqIdValue",prefix+f.getName()+suffix);
          	}else{
          		captions.put(f.getName(),caption.value());
          	}
          	
          	fields.put( f.getName(),prefix+f.getName()+suffix);
          	listCaptions.put(prefix+f.getName()+suffix, caption.value());
			}
          //Input
          inputParamMap.put("fields", fields);  
          inputParamMap.put("captions", captions); 
          //List
          listParamMap.put("listCaptions", listCaptions); 
          listParamMap.put("page", "page"); 
          listParamMap.put("fields", fields);  
          listParamMap.put("pageNumber", "${page.pageNumber}");
          listParamMap.put("totalPages", "${page.totalPages}");
          listParamMap.put("search", "search"); 
          
          Writer writer  = new OutputStreamWriter(new FileOutputStream(bean.getClass().getSimpleName()+"Input.jsp"),"UTF-8"); 
          Writer writer2 = new OutputStreamWriter(new FileOutputStream(bean.getClass().getSimpleName()+"List.jsp"),"UTF-8");
          Writer writer3 = new OutputStreamWriter(new FileOutputStream(bean.getClass().getSimpleName()+"View.jsp"),"UTF-8");

          template.process(inputParamMap, writer);  
          template2.process(listParamMap, writer2);
          template3.process(inputParamMap, writer3); 
          System.out.println("恭喜,生成成功~~");  
      } catch (IOException e) {  
          e.printStackTrace();  
      } catch (TemplateException e) {  
          e.printStackTrace();  
      } 
}*/
	
}

基本java代码都在上面了 有需要ftl模板的可以加我QQ:964388652 但是每个人实现都不同 熟悉一下freemarker就能写出简单的代码生成了 这里的代码就做了简单的划分 没有做得很好 扩展性也没有弄 后面笔者有时间会慢慢完善 把代码重构 毕竟是工作要用的东西,但是基本的思路是不变的,且本人最近也在开始读effective java 感觉自己的java写的安全性,扩展性都没有,但是笔者会不断学习 做一个合格的程序员!

相关阅读

请问一下现在好多淘宝装修代码生成器

请问这些软件是如何做出来的,真的好想自己做一个,因为自己有比较全的代码,但每次都要手动潜换商品图片,真的比较累哇。

WMI代码生成器怎么使用 WMI Code Creator使用详细图文

WMI是一种轻松获取系统信息的强大工具。利用它但是由于缺少WMI的介绍资料和学习资料(特别是中文的,因为国内大部分程序员的E文水平

分享到:

猜你喜欢

    Warning: mysql_query(): Unable to save result set in E:wwwwww.seotesttools.comeclassdb_sql.php on line 20 SQL Error: select id,classid,ttid,onclick,plnum,totaldown,newspath,filename,userid,username,firsttitle,isgood,ispic,istop,isqf,ismember,isurl,truetime,lastdotime,havehtml,groupid,userfen,titlefont,titleurl,stb,fstb,restb,keyboard,title,ftitle,newstime,titlepic,smalltext,diggtop from ***_ecms_news order by rand() limit 6

栏目导航

推荐阅读

热门阅读

    Warning: mysql_query(): Unable to save result set in E:wwwwww.seotesttools.comeclassdb_sql.php on line 20 SQL Error: select id,classid,ttid,onclick,plnum,totaldown,newspath,filename,userid,username,firsttitle,isgood,ispic,istop,isqf,ismember,isurl,truetime,lastdotime,havehtml,groupid,userfen,titlefont,titleurl,stb,fstb,restb,keyboard,title,ftitle,newstime,titlepic,smalltext,diggtop from ***_ecms_news where isgood>0 order by rand() limit 30