mybatis自动生成xml等文件

 

GenerateParamsUtil类

import java.io.*;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Date;

/**
 * cmbxb	55.12.221.63/55.12.205.225	3306		app_usr/App_usr@2018
 * cma11	55.12.221.57/55.12.205.219	3306		app_usr/App_usr@2018

 */
public class GenerateParamsUtil {
    private final String bean_path = "d:/generator/bean";//生成到指定路径
    private final String xml_path = "d:/generator/xml";
    private final String txt_path = "d:/generator/txt";
    private final String mapper_path = "d:/generator/mapper";
    private final String bean_package = "com.cmb.dw.rtl.yearbil.dao.yearbil";
    private final String mapper_namespace = "com.cmb.dw.rtl.yearbil.dao.yearbil";
    private final String mapper_package = "com.cmb.dw.rtl.yearbil.dao.yearbil";
    private final String driverName = "com.mysql.jdbc.Driver";
    private final String user = "app_usr";
    private final String password = "App_usr@2018";
    private final String url = "jdbc:mysql://55.12.221.57:3306/cmb2r1?characterEncoding=utf-8";
    private Connection conn = null;
    static Map<String,String> tables =new HashMap<String, String>();
    static{
        tables.put("artc_r_cb_pb_cust_uid_mng_inf", "CustUidMngInfOutParams");
    }
	/**
     *
    * @Title: init
    * @Description: 连接数据库
    * @param @throws ClassNotFoundException
    * @param @throws SQLException    设定文件
    * @return void    返回类型
    * @throws
     */
    private void init() throws ClassNotFoundException, SQLException {
        Class.forName(driverName);
        conn = DriverManager.getConnection(url, user, password);
    }

    public void generate() throws ClassNotFoundException, SQLException, IOException {
        init();
        String prefix = "show full fields from ";
        List<String> columns = null;
        List<String> types = null;
        List<String> comments = null;
        PreparedStatement pstate = null;
        Map<String, String> tableComments = getTableComment();
        for ( String table : tables.keySet() ) {
            columns = new ArrayList<String>();
            types = new ArrayList<String>();
            comments = new ArrayList<String>();
            pstate = conn.prepareStatement(prefix + table);
            ResultSet results = pstate.executeQuery();
            while ( results.next() ) {
                columns.add(results.getString("FIELD"));
                types.add(results.getString("TYPE"));
                comments.add(results.getString("COMMENT"));
            }
            String entityName=tables.get(table);
            String tableComment = tableComments.get(table);
            buildEntityBean(entityName,columns, types, comments, tableComment);
            buildMapperXml(entityName,columns, types, table);
            buildBeanTxt(entityName, columns, comments);
            //buildMapperDao(entityName,columns, types, comments, tableComment);
        }
        conn.close();
    }

    /**
     *
    * @Title: processType
    * @Description: 字段类型都为String
    * @param @param type
    * @param @return    设定文件
    * @return String    返回类型
    * @throws
     */
    private String processType( String type ) {
            return "String";
    }


    /**
     *  生成实体类
     *
     * @param columns
     * @param types
     * @param comments
     * @throws java.io.IOException
     */
    private void buildEntityBean(String entityName, List<String> columns, List<String> types, List<String> comments, String tableComment )
        throws IOException {
        File folder = new File(bean_path);
        if ( !folder.exists() ) {
            folder.mkdir();
        }

        File beanFile = new File(bean_path, entityName + ".java");
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(beanFile)));
        bw.write("package " + bean_package + ";");
        bw.newLine();
        bw.write("import java.io.Serializable;");
        bw.newLine();
        bw = buildClassComment(bw, entityName,tableComment);
        bw.newLine();
        bw.write("public class " + entityName + " implements Serializable {");
        bw.newLine();
        bw.write("\tprivate static final long serialVersionUID = 8929159233764146422L;");
        bw.newLine();
        int size = columns.size();
        for ( int i = 0 ; i < size ; i++ ) {
            bw.write("\t/**" + comments.get(i) + "**/");
            bw.newLine();
            bw.write("\tprivate " + processType(types.get(i)) + " " + processField(columns.get(i)) + ";");
            bw.newLine();
            bw.newLine();
        }
        bw.newLine();
        // 生成get 和 set方法
        String tempField = null;
        String _tempField = null;
        String tempType = null;
        for ( int i = 0 ; i < size ; i++ ) {
            tempType = processType(types.get(i));
            _tempField = processField(columns.get(i));
            tempField = _tempField.substring(0, 1).toUpperCase() + _tempField.substring(1);
            bw.newLine();
            //          bw.write("\tpublic void set" + tempField + "(" + tempType + " _" + _tempField + "){");
            bw.write("\tpublic void set" + tempField + "(" + tempType + " " + _tempField + "){");
            bw.newLine();
            //          bw.write("\t\tthis." + _tempField + "=_" + _tempField + ";");
            bw.write("\t\tthis." + _tempField + " = " + _tempField + ";");
            bw.newLine();
            bw.write("\t}");
            bw.newLine();
            bw.newLine();
            bw.write("\tpublic " + tempType + " get" + tempField + "(){");
            bw.newLine();
            bw.write("\t\treturn this." + _tempField + ";");
            bw.newLine();
            bw.write("\t}");
            bw.newLine();
        }
        bw.newLine();
        bw.write("}");
        bw.newLine();
        bw.flush();
        bw.close();
    }

    private String processField( String field ) {
        StringBuffer sb = new StringBuffer(field.length());
        //field = field.toLowerCase();
        String[] fields = field.split("_");
        String temp = null;
        sb.append(fields[0].toLowerCase());
        for ( int i = 1 ; i < fields.length ; i++ ) {
            temp = fields[i].trim();
            sb.append(temp.substring(0, 1).toUpperCase()).append(temp.substring(1).toLowerCase());
        }
        return sb.toString();
    }


    /**
     *  构建类上面的注释
     *
     * @param bw
     * @param text
     * @return
     * @throws java.io.IOException
     */
    private BufferedWriter buildClassComment( BufferedWriter bw,String entityName, String text ) throws IOException {
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    	bw.newLine();
        bw.newLine();
        bw.write("/**");
        bw.newLine();
        bw.write(" * ");
        bw.newLine();
        bw.write(" *@ClassName: " + entityName);
        bw.newLine();
        bw.write(" *@Description:"+text);
        bw.newLine();
        bw.write(" *@author:lvyanghui");
        bw.newLine();
        bw.write(" *@date:"+sdf.format(new Date()));
        bw.newLine();
        bw.write(" **/");
        return bw;
    }


    /**
     *  构建实体类映射XML文件
     *
     * @param columns
     * @param types
     * @param table
     * @throws java.io.IOException
     */
    private void buildMapperXml(String entityName, List<String> columns, List<String> types,String table) throws IOException {
        File folder = new File(xml_path);
        if ( !folder.exists() ) {
            folder.mkdirs();
        }
        File mapperXmlFile = new File(xml_path, entityName + ".xml");
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(mapperXmlFile)));
        bw.write("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
        bw.newLine();
        bw.write("<!DOCTYPE mapper PUBLIC \"-//mybatis.org//DTD Mapper 3.0//EN\" \"http://www.mybatis.org/dtd/mybatis-3-mapper.dtd\">");
        bw.newLine();
        bw.write("<mapper namespace=\"" + mapper_namespace+"\">");
        bw.newLine();
        bw.newLine();
        buildResultMap(entityName,bw, columns);
        bw.newLine();
        bw.newLine();
        buildSqlList(entityName, bw, columns);
        bw.newLine();
        bw.newLine();
        buildSelectSql(entityName,bw,columns,table);
        bw.newLine();
        bw.newLine();
        buildInsertSql(entityName,bw,columns,table);
        bw.newLine();
        bw.newLine();
        buildUpdateSql(entityName,bw,columns,table);
        bw.newLine();
        bw.newLine();
        buildDeleteSql(entityName,bw,columns,table);
        bw.newLine();
        bw.newLine();
        bw.write("</mapper>");
        bw.flush();
        bw.close();
    }

    private void buildResultMap(String entityName,BufferedWriter bw, List<String> columns) throws IOException {

        bw.write("    <resultMap type=\""+bean_package+"."+entityName+"\" id=\""+entityName+"Map\">");
        bw.newLine();
        int size = columns.size();
        for ( int i = 0 ; i < size ; i++ ) {
            bw.write("        <result property=\""+ processField(columns.get(i))+"\"    column=\""+columns.get(i)+"\"/>");
            bw.newLine();
        }
        bw.write("    </resultMap>");
    }

    private void buildSqlList(String entityName,BufferedWriter bw, List<String> columns) throws IOException {

        bw.write("    <sql id=\"" + entityName + "List\">");
        bw.newLine();
        int size = columns.size();
        for ( int i = 0 ; i < size ; i++ ) {
            if(i == size - 1){
                bw.write("        " + columns.get(i));
                bw.newLine();
            }else{
                bw.write("        " + columns.get(i) + ",");
                bw.newLine();
            }
        }
        bw.write("    </sql>");
    }

    private void buildSelectSql(String entityName,BufferedWriter bw, List<String> columns, String table)throws IOException{
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        String selectId = "search" + entityName.replace("OutParams","") + "Pb";
        String resultMap = entityName + "Map";
        bw.write("    <!-- 请填写注释 lvyanghui " + dateFormat.format(calendar.getTime()) + " --> ");
        bw.newLine();
        bw.write("    <select id=\"" + selectId + "\" resultMap=\"" + resultMap + "\"");
        bw.newLine();
        bw.write("            parameterType=\"" + bean_package + "." + entityName + "\">");
        bw.newLine();
        bw.write("        SELECT");
        bw.newLine();
        bw.write("            <include refid=\"" + entityName + "List\"></include>");
        bw.newLine();
        bw.write("        FROM");
        bw.newLine();
        bw.write("            "+table);
        bw.newLine();
        bw.write("        WHERE");
        bw.newLine();
        bw.write("            " + columns.get(0) + " = #{" + processField(columns.get(0)) + "}");
        bw.newLine();
        bw.write("    </select>");
    }

    private void buildInsertSql(String entityName,BufferedWriter bw, List<String> columns, String table)throws IOException{
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        String insertId = "insert" + entityName.replace("OutParams","") + "Pb";
        bw.write("    <!-- 请填写注释 lvyanghui " + dateFormat.format(calendar.getTime()) + " --> ");
        bw.newLine();
        bw.write("    <insert id=\"" + insertId + "\" ");
        bw.newLine();
        bw.write("            parameterType=\"" + bean_package + "." + entityName + "\">");
        bw.newLine();
        bw.write("        INSERT INTO " + table );
        bw.newLine();
        bw.write("            (");
        bw.newLine();
        int size = columns.size();
        for (int i = 0; i < size; i++) {
            if(i == size - 1){
                bw.write("            " + columns.get(i));
            }else{
                bw.write("            " + columns.get(i) + ",");
                bw.newLine();
            }
        }
        bw.newLine();
        bw.write("            )");
        bw.newLine();
        bw.write("            VALUES");
        bw.newLine();
        bw.write("            (");
        bw.newLine();
        for (int i = 0; i < size; i++) {
            if(i == size - 1){
                bw.write("            #{" + processField(columns.get(i)) + "}");
            }else{
                bw.write("            #{" + processField(columns.get(i)) + "},");
                bw.newLine();
            }
        }
        bw.newLine();
        bw.write("            )");
        bw.newLine();
        bw.write("    </insert>");
    }

    private void buildUpdateSql(String entityName,BufferedWriter bw, List<String> columns, String table)throws IOException{
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        String updateId = "update" + entityName.replace("OutParams","") + "Pb";
        bw.write("    <!-- 请填写注释 lvyanghui " + dateFormat.format(calendar.getTime()) + " --> ");
        bw.newLine();
        bw.write("    <update id=\"" + updateId + "\" ");
        bw.newLine();
        bw.write("            parameterType=\"" + bean_package + "." + entityName + "\">");
        bw.newLine();
        bw.write("        UPDATE " + table );
        bw.newLine();
        bw.write("        SET");
        bw.newLine();
        int size = columns.size();
        for (int i = 0; i < size; i++) {
            if(i == size - 1){
                bw.write("            " + columns.get(i) + " = #{" + processField(columns.get(i)) + "}");
            }else{
                bw.write("            " + columns.get(i) + " = #{" + processField(columns.get(i)) + "},");
                bw.newLine();
            }
        }
        bw.newLine();
        bw.write("        WHERE");
        bw.newLine();
        bw.write("            " + columns.get(0) + " = #{" + processField(columns.get(0)) + "}");
        bw.newLine();
        bw.write("    </update>");
    }

    private void buildDeleteSql(String entityName,BufferedWriter bw, List<String> columns, String table)throws IOException{
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        String deleteId = "delete" + entityName.replace("OutParams","") + "Pb";
        bw.write("    <!-- 请填写注释 lvyanghui " + dateFormat.format(calendar.getTime()) + " --> ");
        bw.newLine();
        bw.write("    <delete id=\"" + deleteId + "\" ");
        bw.newLine();
        bw.write("            parameterType=\"" + bean_package + "." + entityName + "\">");
        bw.newLine();
        bw.write("        DELETE FROM " + table );
        bw.newLine();
        bw.write("        WHERE");
        bw.newLine();
        bw.write("            " + columns.get(0) + " = #{" + processField(columns.get(0)) + "}");
        bw.newLine();
        bw.write("    </delete>");
    }

    /**
     * 生成字段加注释txt文件
     * @param entityName
     * @param columns
     * @param comments
     * @throws java.io.IOException
     */
    public void buildBeanTxt(String entityName, List<String> columns, List<String> comments)throws IOException{
        File folder = new File(txt_path);
        if ( !folder.exists() ) {
            folder.mkdir();
        }

        File txtFile = new File(txt_path, entityName + ".txt");
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(txtFile)));
        int size = columns.size();
        for (int i = 0; i < size; i++) {
            bw.write(processField(columns.get(i)) + "    " + comments.get(i));
            bw.newLine();
        }
        bw.flush();
        bw.close();
    }

    /**
     *  生成dao层
     *
     * @param columns
     * @param types
     * @param comments
     * @throws java.io.IOException
     */
    private void buildInterfaceDao(String entityName, List<String> columns, List<String> types, List<String> comments, String tableComment )
            throws IOException {
        File folder = new File(mapper_path);
        if ( !folder.exists() ) {
            folder.mkdir();
        }

        String fileName = entityName.replace("OutParams","") + "Dao.java";
        File beanFile = new File(fileName);
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(beanFile)));
        bw.write("package " + mapper_package + ";");
        bw.newLine();
        bw.write("import " + bean_package + entityName + ";");
        bw.newLine();
        bw.write("import com.cmb.framework.exception.FrameworkException;");
        bw.newLine();
        bw = buildClassComment(bw, entityName,tableComment);
        bw.newLine();
        bw.write("public class " + entityName + " implements Serializable {");
        bw.newLine();
        bw.write("\tprivate static final long serialVersionUID = 8929159233764146422L;");
        bw.newLine();
        int size = columns.size();
        for ( int i = 0 ; i < size ; i++ ) {
            bw.write("\t/**" + comments.get(i) + "**/");
            bw.newLine();
            bw.write("\tprivate " + processType(types.get(i)) + " " + processField(columns.get(i)) + ";");
            bw.newLine();
            bw.newLine();
        }
        bw.newLine();
        // 生成get 和 set方法
        String tempField = null;
        String _tempField = null;
        String tempType = null;
        for ( int i = 0 ; i < size ; i++ ) {
            tempType = processType(types.get(i));
            _tempField = processField(columns.get(i));
            tempField = _tempField.substring(0, 1).toUpperCase() + _tempField.substring(1);
            bw.newLine();
            //          bw.write("\tpublic void set" + tempField + "(" + tempType + " _" + _tempField + "){");
            bw.write("\tpublic void set" + tempField + "(" + tempType + " " + _tempField + "){");
            bw.newLine();
            //          bw.write("\t\tthis." + _tempField + "=_" + _tempField + ";");
            bw.write("\t\tthis." + _tempField + " = " + _tempField + ";");
            bw.newLine();
            bw.write("\t}");
            bw.newLine();
            bw.newLine();
            bw.write("\tpublic " + tempType + " get" + tempField + "(){");
            bw.newLine();
            bw.write("\t\treturn this." + _tempField + ";");
            bw.newLine();
            bw.write("\t}");
            bw.newLine();
        }
        bw.newLine();
        bw.write("}");
        bw.newLine();
        bw.flush();
        bw.close();
    }
    /**
     *  获取所有的数据库表注释
     *
     * @return
     * @throws java.sql.SQLException
     */
    private Map<String, String> getTableComment() throws SQLException {
        Map<String, String> maps = new HashMap<String, String>();
        PreparedStatement pstate = conn.prepareStatement("show table status");
        ResultSet results = pstate.executeQuery();
        while ( results.next() ) {
            String tableName = results.getString("NAME");
            if(tables.containsKey(tableName)){
            	   String comment = results.getString("COMMENT");
                   maps.put(tableName, comment);
        	}
         
        }
        return maps;
    }
    
 
 
    public static void main( String[] args ) {
        try {
            new GenerateParamsUtil().generate();
            // 自动打开生成文件的目录
            //Runtime.getRuntime().exec("cmd /c start explorer D:\\");
        } catch ( ClassNotFoundException e ) {
            e.printStackTrace();
        } catch ( SQLException e ) {
            e.printStackTrace();
        } catch ( IOException e ) {
            e.printStackTrace();
        }
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值