freemaker代码生成器

阅读更多

介绍:

        根据表结构生成mybatis对应的实现体和Mpper.xml文件,我们使用的是mysql数据库

需要的jar包 freemarker.jar mysql.jar 如附件

 

1. 数据库连接类

 

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * 数据库连接设置
 * 
 * @author king
 * 2014-5-5
 */
public class DBConnectionUtils {
	private static Connection conn = null;
 
	public static Connection getJDBCConnection() {
		if (null == conn) {
			try {
				Class.forName("com.mysql.jdbc.Driver"); // 
				String url = "jdbc:mysql://127.0.0.1:3306/risk_monitor";//
				String user = "root";
				String password = "root";
				conn = DriverManager.getConnection(url, user, password);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return conn;
	}

	public static void close(){
		if(null!=conn){
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	
}

 2. column类

 

    

public class Column {

	private String columnName;
	private String columnType;
	private String attributeName;
	private String attributeType;
	public String getColumnName() {
		return columnName;
	}
	public void setColumnName(String columnName) {
		this.columnName = columnName;
	}
	public String getColumnType() {
		return columnType;
	}
	public void setColumnType(String columnType) {
		this.columnType = columnType;
	}
	public String getAttributeName() {
		return attributeName;
	}
	public void setAttributeName(String attributeName) {
		this.attributeName = attributeName;
	}
	public String getAttributeType() {
		return attributeType;
	}
	public void setAttributeType(String attributeType) {
		this.attributeType = attributeType;
	}

}

 

3. generator类

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;


public class Generator {
	private Configuration cfg;
	private Connection connection;
	private void initial() {
		try {
			if (null == cfg) {
				cfg = new Configuration();
			}
			cfg.setDirectoryForTemplateLoading(new File(
					"src/com/chinaebi/codegen/template"));
			connection = DBConnectionUtils.getJDBCConnection();
		} catch (IOException e) {
			e.printStackTrace();
		}
		cfg.setObjectWrapper(new DefaultObjectWrapper());
	}
	public void generator() throws Exception {
		initial();
		cfg.setDefaultEncoding("utf-8");
		Template entityTemplate = cfg.getTemplate("entity.ftl");
		Template sqlTemplate = cfg.getTemplate("sql.ftl");
		List> templates = generatorTemplateData();

		for (Map o : templates) {
//			Writer out = new OutputStreamWriter(System.out);//
//			打印到控制台
//			Writer outFile = new OutputStreamWriter(new FileOutputStream(
//					"src/com/chinaebi/codegen/template/"+o.get("tableName")+".java"), "gb2312");
//			entityTemplate.process(o, out);
//			entityTemplate.process(o, outFile);
//			out.flush();
			//输出到文件
	        File beanFile = new File("src/com/chinaebi/codegen/template/entity/"+o.get("beanName")+".java");  
	        Writer beanWriter = new FileWriter(beanFile); 
	        entityTemplate.process(o, beanWriter);  
	        beanWriter.close(); 
	        File sqlFile = new File("src/com/chinaebi/codegen/template/sql/Tbl_"+o.get("beanName")+"Mapper.xml");  
	        Writer sqlWriter = new FileWriter(sqlFile);  
	        sqlTemplate.process(o, sqlWriter);  
	        sqlWriter.close(); 
	        System.out.println("生成:"+o.get("beanName"));
		}
	}


	private List> generatorTemplateData() throws Exception {
		DatabaseMetaData dbmd = connection.getMetaData();
		List> lists = new ArrayList>();
		String[] tables = { "Table" };
		ResultSet tableSet = dbmd.getTables(null, null, "%", tables);//
		while (tableSet.next()) {
			Map map = new HashMap();
			String tableName = tableSet.getString("TABLE_NAME");
			ResultSet columnSet = dbmd.getColumns(null, "%", tableName, "%");
			List columns = new ArrayList();// 
			while (columnSet.next()) {

				String columnName = columnSet.getString("COLUMN_NAME");
				String attributeName = handlerColumnName(columnSet.getString("COLUMN_NAME"));
				String columnType = columnSet.getString("TYPE_NAME");
				String attributeType = handlerColumnType(columnSet.getString("TYPE_NAME"));
				Column column = new Column();
				column.setColumnName(columnName);
				column.setColumnType(columnType);
				column.setAttributeName(attributeName);
				column.setAttributeType(attributeType);
				columns.add(column);
			}
			map.put("tableName", tableName);
			map.put("beanName", handlerTableName(tableName));
			map.put("columns", columns);
			lists.add(map);
		}
		connection.close();
		return lists;
	}

	public static String handlerColumnName(String oldName) {
		String[] arrays = oldName.split("_");
		String newName = "";
		if (arrays.length > 0) {
			newName = arrays[0];
		}
		for (int i = 1; i < arrays.length; i++) {
			newName += (arrays[i].substring(0, 1).toUpperCase() + arrays[i]
					.substring(1, arrays[i].length()));
		}
		return newName;
	}

	public static String handlerTableName(String oldName) {
		String[] arrays = oldName.split("_");
		String newName = "";
		for (int i = 0; i < arrays.length; i++) {
			newName += (arrays[i].substring(0, 1).toUpperCase() + arrays[i]
					.substring(1, arrays[i].length()));
		}
		return newName;
	}

	public static String handlerColumnType(String oldType) {
		if (oldType.toUpperCase().startsWith("VARCHAR")) {
			return "String";
		}
		if (oldType.toUpperCase().startsWith("INT")) {
			return "int";
		}
		if (oldType.toUpperCase().startsWith("DATETIME")) {
			return "Date";
		}if (oldType.toUpperCase().startsWith("CHAR")) {
			return "String";
		}
		if (oldType.toUpperCase().startsWith("TINYINT")) {
			return "int";
		}
		if (oldType.toUpperCase().startsWith("BIT")) {
			return "int";
		}
		if (oldType.toUpperCase().startsWith("BIGINT")) {
			return "BigInteger";
		}
		return oldType;
	}
}

 4.运行方法

/**
 * 运行方法
 * 
 * @author king
 * 2014-5-5
 */
public class Main {
	public static void main(String[] args) throws Exception {
		Generator gen = new Generator();
		gen.generator();
	}
}

 4. 模板

    entity.ftl

   

/**
 * 对应表 ${tableName}
 * @author king
 *
 */
public class ${beanName} implements java.io.Serializable{
 <#list columns as item>
  private ${item.attributeType} ${item.attributeName};/*对应表中${item.columnName}*/
 
 <#list columns as item>  
    public ${item.attributeType} get${item.attributeName?cap_first}(){  
      return ${item.attributeName};  
    }  
    public void set${item.attributeName?cap_first}(${item.attributeType} ${item.attributeName}){  
      this.${item.attributeName} = ${item.attributeName};  
    }  
    
}

    sql.ftl

  




 

	
		 <#list columns as item>
		 	
		 
	
    
	
	
	
	
	
	
	
		insert into ${tableName}(
			<#list columns as item>
				${item.columnName},
			
		) values(<#list columns as item>
				${'#'}{${item.attributeName}},
			)
	
	
	
		update ${tableName} set 
		<#list columns as item>
    		
    			 t.${item.columnName} = ${'#'}{${item.attributeName}},
    		
        
		where
		1=1
		<#list columns as item>
    		
    			and  t.${item.columnName} = ${'#'}{${item.attributeName}}
    		
        
	
	
	
		delete from ${tableName} where 1=1
		<#list columns as item>
    		
    			and t.${item.columnName} = ${'#'}{${item.attributeName}}
    		
        
	




	

 

    

      

  • freemarker-2.3.15.jar (858.7 KB)
  • 下载次数: 22
  • mysql-connector-java-5.1.18-bin.jar (771.4 KB)
  • 下载次数: 11

你可能感兴趣的:(freemaker)