自動生成MyBatis的實體類、實體映射XML文件、Mapper(暫時只適用mysql)

package com.ophiux;

import org.apache.commons.lang3.StringUtils;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
import java.text.SimpleDateFormat;

/**
 * 說明:自動生成MyBatis的實體類、實體映射XML文件、Mapper(暫時只適用mysql)<br>
 * <h1>創 建 人: hhl </h1>
 * 創建日期: 2019年1月29日 下午4:15:18<br>
 * 需要jar:mysql-connector-java,commons-lang3
 */
public class EntityUtil {
    /**
     * 數據庫數據類型
     */
    private final static String type_char = "char";
    private final static String type_date = "date";
    private final static String type_timestamp = "timestamp";
    private final static String type_int = "int";
    private final static String type_bigint = "bigint";
    private final static String type_text = "text";
    private final static String type_bit = "bit";
    private final static String type_decimal = "decimal";
    private final static String type_blob = "blob";
    private final static String type_double = "double";

    /**
     * 文件生成位置配置
    */
    /** 生成的entity文件存放路徑 */
    private final String bean_path = "C:/Users/Administrator/Desktop";
    /** 生成的mapper文件存放路徑*/
    private final String mapper_path = "C:/Users/Administrator/Desktop";
    /** 生成的XML文件存放路徑*/
    private final String xml_path = "C:/Users/Administrator/Desktop";
    /** 實體類所屬項目路徑(根據自己做的項目相應調整)*/
    private static final String bean_package = "com.ophiux.FeverManagement.domain.entity";
    /** Mapper類所屬項目路徑(根據自己做的項目相應調整)*/
    private final String mapper_package = "com.ophiux.FeverManagement.infratructure.mapper";
    /** 基礎實現類所屬項目路徑 ps:項目沒有基礎實現類請將該值變成空串*/
    private final String base_package = "";
    private final String driverName = "com.mysql.jdbc.Driver";
    /** 數據庫用戶名 */
    private final String user = "root";
    /** 數據庫密碼 */
    private final String password = "root";
    /** 數據庫名稱(根據自己模塊做相應調整) */
    private final String moduleName = "ophiux_hot_diseases";
    /** 數據庫連接(根據自己模塊做相應調整)*/
    private final String url = "jdbc:mysql://192.168.6.11:3306/" + moduleName + "?&useUnicode=true&useSSL=false&characterEncoding=utf8";
    /** 表名(需要生成的表)*/
    private static String tableName = "hp_user";
    private static String beanName = null;
    private String mapperName = null;
    private Connection conn = null;
    /** 使用的持久層框架 M:MyBatis H:Hibernate */
    private String persistence_frame = "M";
    /** 是否序列化  Y:是  N:否 */
    private String serializable = "N";


    public static void main(String[] args) {
        try {
            System.out.println("=========開始生成=========");
            new EntityUtil().generate();
            System.out.println("=========生成結束=========");
            // 自動打開生成文件的目錄
            //Runtime.getRuntime().exec("cmd /c start explorer D:\\code\\");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    public void generate() throws ClassNotFoundException, SQLException, IOException {
        System.out.println("==========生成中==========");
        init();
        //查詢表所有的列信息
        String prefix = "show full fields from ";
        List<String> columns = null;
        List<String> types = null;
        List<String> comments = null;
        PreparedStatement pstate;
        columns = new ArrayList<String>();
        types = new ArrayList<String>();
        comments = new ArrayList<String>();
        pstate = conn.prepareStatement(prefix + tableName);
        ResultSet results = pstate.executeQuery();
        while (results.next()) {
        	//字段名
            columns.add(results.getString("FIELD"));
            //字段類型
            types.add(results.getString("TYPE"));
            //字段註釋
            comments.add(results.getString("COMMENT"));
        }
        
        //查詢表信息
        String prefix2 = "show table status where name='"+tableName+"'";
        PreparedStatement  pstate2 = conn.prepareStatement(prefix2);
        ResultSet results2 = pstate2.executeQuery();
        //表註釋
        String tableComment = "";
        while(results2.next()) {
        	tableComment = results2.getString("COMMENT");
        }
        
        processTable(tableName);
        buildEntityBean(columns, types, comments, tableName,tableComment);
        //使用MyBatis才生成Mapper文件
        if (persistence_frame.equals("M")) {
            buildMapper(types);
            buildMapperXml(columns, types, comments);
        }
        conn.close();
    }
    

    /**
     * 說明:初始化連接數據庫 <br>
     * 創 建 人: hhl
     * @throws ClassNotFoundException
     * @throws SQLException
     */
    private void init() throws ClassNotFoundException, SQLException {
        Class.forName(driverName);
        conn = DriverManager.getConnection(url, user, password);
    }
    
    /**
     * 說明: 獲取所有的數據庫表註釋<br>
     * 創 建 人: hhl
     * @return
     * @throws SQLException
     */
    @SuppressWarnings("unused")
	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");
            String comment = results.getString("COMMENT");
            maps.put(tableName, comment);
        }
        return maps;
    }
    

    /**
     * 說明: 獲取所有的表<br>
     * 創 建 人: hhl
     * @return	List表集合
     * @throws SQLException
     */
    @SuppressWarnings("unused")
	private List<String> getTables() throws SQLException {
        List<String> tables = new ArrayList<String>();
        PreparedStatement pstate = conn.prepareStatement("show tables");
        ResultSet results = pstate.executeQuery();
        while (results.next()) {
        	String tableName = results.getString(1);
            if ( tableName.toLowerCase().startsWith("ophiux_") ) {
            	tables.add(tableName);
            }
        }
        return tables;
    }


    /**
     * 說明: 生成Mapper文件名<br>
     * 創 建 人: hhl
     * @param table 表名
     */
    private void processTable(String table) {
        StringBuilder sb = new StringBuilder(table.length());
        String tableNew = table.toLowerCase();
        String[] tables = tableNew.split("_");
        String temp;
        for (String table1 : tables) {
            temp = table1.trim();
            sb.append(temp.substring(0, 1).toUpperCase()).append(temp.substring(1));
        }
        beanName = sb.toString();
        mapperName = beanName + "Mapper";
    }


    /**
     * 數據庫數據類型與Java數據類型轉換
     */
    private static String processType(String type) {
    	//萬能字符串
    	if("1".equals("1")) {
    		return "String";
    	}
        if (type.contains(type_char)) {
            return "String";
        } else if (type.contains(type_bigint)) {
            return "Long";
        } else if (type.contains(type_int)) {
            if (type.startsWith(type_int) && type.contains("unsigned")) {
                return "Long";
            } else {
                return "Integer";
            }
        } else if (type.contains(type_date)) {
            return "java.util.Date";
        } else if (type.contains(type_text)) {
            return "String";
        } else if (type.contains(type_timestamp)) {
            return "java.util.Date";
        } else if (type.contains(type_bit)) {
            return "Boolean";
        } else if (type.contains(type_decimal)) {
            return "java.math.BigDecimal";
        } else if (type.contains(type_blob)) {
            return "byte[]";
        } else if (type.contains(type_double)) {
            return "Double";
        }
        return type;
    }


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


    /**
     * 將實體類名首字母改爲小寫
     */
    private static String processResultMapId(String beanName) {
        return beanName.substring(0, 1).toLowerCase() + beanName.substring(1);
    }

    /**
     * 說明: 構建類上面的註釋<br>
     * 創 建 人: hhl
     * @param bw
     * @param tableComment		表註釋
     * @return
     * @throws IOException
     */
    private BufferedWriter buildClassComment(BufferedWriter bw, String tableComment) throws IOException {
        bw.newLine();
        bw.newLine();
        bw.write("/**");
        //bw.newLine();
        //bw.write(" * ");
        bw.newLine();
        bw.write(" * 說明:" + tableComment);
        bw.newLine();
        bw.write(" * <h1>創建人: hhl </h1>");
        bw.newLine();
        bw.write(" * 創建日期: " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+"<br>");
        bw.newLine();
        bw.write(" **/");
        return bw;
    }


    /**
     * 說明: 構建方法上面的註釋<br>
     * 創 建 人: hhl
     * @param bw
     * @param text	註釋
     * @return
     * @throws IOException
     */
    private BufferedWriter buildMethodComment(BufferedWriter bw, String text) throws IOException {
        bw.newLine();
        bw.write("\t/**");
        bw.newLine();
        bw.write("\t * " + text);
        bw.newLine();
        bw.write("\t **/");
        return bw;
    }

    /**
     * 說明: 構建屬性(字段)上面的註釋<br>
     * 創 建 人: hhl
     * @param bw
     * @param text 註釋
     * @return
     * @throws IOException
     */
    private BufferedWriter buildFieldComment(BufferedWriter bw, String text) throws IOException {
        bw.newLine();
        if (null != text && !text.trim().equals("")) {
            bw.write("\t/**");
            bw.newLine();
            bw.write("\t * " + text);
            bw.newLine();
            bw.write("\t */");
        }
        return bw;
    }


    /**
     * 說明: 生成實體類<br>
     * 創 建 人: hhl
     * @param columns	字段名集合
     * @param types		字段類型集合
     * @param comments	字段註釋
     * @param tableName		表名
     * @param tableComment	表註釋
     * @throws IOException
     */
    private void buildEntityBean(List<String> columns, List<String> types, List<String> comments, String tableName, String tableComment)
            throws IOException {
        File folder = new File(bean_path);
        if (!folder.exists()) {
            folder.mkdirs();
        }

        File beanFile = new File(bean_path, beanName + ".java");
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(beanFile)));
        bw.write("package " + bean_package + ";");
        bw.newLine();

        //region 包引入
        bw.newLine();
        if("Y".equals(serializable)) {
        	bw.write("import java.io.Serializable;");
        }
        if (persistence_frame.equals("M")) {
//            bw.newLine();
//            bw.write("import lombok.AllArgsConstructor;");
//            bw.newLine();
//            bw.write("import lombok.Builder;");
        	bw.newLine();
        	bw.write("import lombok.Getter;");
        	bw.newLine();
        	bw.write("import lombok.Setter;");
//            bw.newLine();
//            bw.write("import lombok.Data;");
//            bw.newLine();
//            bw.write("import lombok.NoArgsConstructor;");
        }
        if (persistence_frame.equals("H")) {
            bw.newLine();
            bw.write("import javax.persistence.*;");
        }
        //endregion

        //region 類註釋
        bw = buildClassComment(bw, tableComment);
        bw.newLine();
        bw.write("");
        //endregion

        //region 是否添加註解
        if (persistence_frame.equals("M")) {
//            bw.newLine();
//            bw.write("@Data");
            bw.newLine();
            bw.write("@Getter");
            bw.newLine();
            bw.write("@Setter");
//            bw.newLine();
//            bw.write("@Builder");
//            bw.newLine();
//            bw.write("@NoArgsConstructor");
//            bw.newLine();
//            bw.write("@AllArgsConstructor");
        }
        if (persistence_frame.equals("H")) {
            bw.newLine();
            bw.write("@Entity");
            bw.newLine();
            bw.write("@Table(name = \"" + tableName + "\")");
        }
        //endregion

        bw.newLine();
        if("Y".equals(serializable)) {
        	bw.write("public class " + beanName + " implements Serializable" + " {");
        }else {
        	bw.write("public class " + beanName + " {");
        }
        
        bw.newLine();
        int size = columns.size();
        for (int i = 0; i < size; i++) {
            buildFieldComment(bw, comments.get(i));
            if (persistence_frame.equals("H")) {
                if (i == 0) {
                    bw.newLine();
                    bw.write("\t@Id");
                }
                bw.newLine();
                bw.write("\t@Column(name = \"" + columns.get(i) + "\")");
            }
            bw.newLine();
            bw.write("\tprivate " + processType(types.get(i)) + " " + processField(columns.get(i)) + ";");
            bw.newLine();
            bw.write("");
        }

        //region 生成get and set
        if (persistence_frame.equals("H")) {
            bw.newLine();
            // 生成get 和 set方法
            String tempField;
            String _tempField;
            String tempType;
            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.newLine();
                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();
            }
        }
        //endregion

        bw.newLine();
        bw.write("}");
        bw.newLine();
        bw.flush();
        bw.close();
    }


    /**
     * 說明: 構建Mapper文件<br>
     * 創 建 人: hhl
     * @param types
     * @throws IOException
     */
    private void buildMapper(List<String> types) throws IOException {
        File folder = new File(mapper_path);
        if (!folder.exists()) {
            folder.mkdirs();
        }

        File mapperFile = new File(mapper_path, mapperName + ".java");
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(mapperFile), "utf-8"));
        bw.write("package " + mapper_package + ";");
        bw.newLine();
        bw.newLine();
        bw.write("import java.util.List;");
        bw.newLine();
        bw.newLine();

        if (StringUtils.isNotEmpty(base_package)) {
            bw.newLine();
            bw.write("import " + base_package + "." + "BaseMapper;");
            bw.newLine();
            bw.write("import " + bean_package + "." + beanName + ";");
        } else {
            bw.newLine();
            bw.write("import " + bean_package + "." + beanName + ";");
        }
        bw.newLine();
        bw.write("import org.springframework.stereotype.Repository;");
        //bw.newLine();
        //bw.write("import org.apache.ibatis.annotations.Param;");
        bw.newLine();
        bw = buildClassComment(bw, mapperName + "數據庫操作接口類");
        bw.newLine();

        bw.write("@Repository");
        if (StringUtils.isNotEmpty(base_package)) {
            bw.newLine();
            bw.write("public interface " + mapperName + " extends BaseMapper<" + beanName + "> " + "{");
        } else {
            bw.newLine();
            bw.write("public interface " + mapperName + "{");
        }
        bw.newLine();
        bw.newLine();

        if (StringUtils.isEmpty(base_package)) {
            // ----------定義Mapper中的方法Begin----------
            bw = buildMethodComment(bw, "查詢(根據主鍵ID查詢)");
            bw.newLine();
            bw.write("\t" + beanName + "  selectByPrimaryKey (" + this.processType(types.get(0)) + " id);");
            bw.newLine();
            bw = buildMethodComment(bw, "查詢(根據條件查詢列表)");
            bw.newLine();
            bw.write("\tList<" + beanName + ">  selectListByParam (" + beanName + " dto);");
            bw.newLine();
            bw = buildMethodComment(bw, "刪除(根據主鍵ID刪除)");
            bw.newLine();
            bw.write("\t" + "int deleteByPrimaryKey (" + this.processType(types.get(0)) + " id);");
            bw.newLine();
            bw = buildMethodComment(bw, "新增");
            bw.newLine();
            bw.write("\t" + "int insert(" + beanName + " record);");
            bw.newLine();
            bw = buildMethodComment(bw, "修改(根據主鍵ID修改)");
            bw.newLine();
            bw.write("\t" + "int update (" + beanName + " record);");
            bw.newLine();
            // ----------定義Mapper中的方法End----------
        }
        bw.newLine();
        bw.write("}");
        bw.flush();
        bw.close();
    }


    /**
     * 說明: 構建實體類映射XML文件<br>
     * 創 建 人: hhl
     * @param columns	字段名集合
     * @param types		字段類型集合
     * @param comments	字段註釋
     * @throws IOException
     */
    private void buildMapperXml(List<String> columns, List<String> types, List<String> comments) throws IOException {
        File folder = new File(xml_path);
        if (!folder.exists()) {
            folder.mkdirs();
        }

        String xmlMapper = beanName + "Mapper";
        File mapperXmlFile = new File(xml_path, xmlMapper + ".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\" ");
        bw.newLine();
        bw.write("    \"http://mybatis.org/dtd/mybatis-3-mapper.dtd\">");
        bw.newLine();
        bw.write("<mapper namespace=\"" + mapper_package + "." + mapperName + "\">");
        bw.newLine();
        bw.newLine();

        bw.write("\t<!--實體映射-->");
        bw.newLine();
        bw.write("\t<resultMap id=\"" + this.processResultMapId(beanName) + "ResultMap\" type=\"" + bean_package + "." + beanName + "\">");
        bw.newLine();
        bw.write("\t\t<!--" + comments.get(0) + "-->");
        bw.newLine();
        bw.write("\t\t<id property=\"" + this.processField(columns.get(0)) + "\" column=\"" + columns.get(0) + "\" />");
        bw.newLine();
        int size = columns.size();
        for (int i = 1; i < size; i++) {
            bw.write("\t\t<!--" + comments.get(i) + "-->");
            bw.newLine();
            bw.write("\t\t<result property=\""
                    + this.processField(columns.get(i)) + "\" column=\"" + columns.get(i) + "\" />");
            bw.newLine();
        }
        bw.write("\t</resultMap>");

        bw.newLine();
        bw.newLine();
        bw.newLine();

        // 下面開始寫SqlMapper中的方法
        buildSQL(bw, columns, types);

        bw.write("</mapper>");
        bw.flush();
        bw.close();
    }

    /**
     * 說明: 構建增、刪、改、查sql語句<br>
     * 創 建 人: hhl
     * @param bw
     * @param columns	字段名集合
     * @param types		字段類型集合
     * @throws IOException
     */
    private void buildSQL(BufferedWriter bw, List<String> columns, List<String> types) throws IOException {
        
    	//創建通用列字段名
    	BaseColumnList(bw, columns, types);
        
        // 通用結果條件
    	ParamSQL(bw, columns, types);

        // 查詢(根據主鍵ID查詢)
    	selectByPrimaryKey(bw, columns, types);
        

        // 查詢(根據條件查詢列表)
    	selectListByParam(bw, columns, types);
    	

        // 刪除(根據主鍵ID刪除)
    	deleteByPrimaryKey(bw, columns, types);


        //新增(匹配有值的字段)
        insert(bw, columns, types);

        // 修改update方法
        update(bw, columns, types);

        bw.newLine();
    }


    /**
     * 說明: 創建sql通用列<br>
     * 創 建 人: hhl
     * @param bw
     * @param columns
     * @param types
     * @throws IOException 
     */
    public static void BaseColumnList(BufferedWriter bw, List<String> columns, List<String> types) throws IOException {
        int size = columns.size();
    	 // 通用結果列
        bw.write("\t<!-- 通用查詢結果列-->");
        bw.newLine();
        bw.write("\t<sql id=\"Base_Column_List\">");
        bw.newLine();

        for (int i = 0; i < size; i++) {
            bw.write("\t\t");
            bw.write(columns.get(i));
            if (i != size - 1) {
                bw.write(",");
                bw.newLine();
            }
        }

        bw.newLine();
        bw.write("\t</sql>");
        bw.newLine();
        bw.newLine();
    }
    
    /**
     * 說明:通用查詢條件 <br>
     * 創 建 人: hhl
     * @param bw
     * @param columns
     * @param types
     * @throws IOException
     */
    public static void ParamSQL(BufferedWriter bw, List<String> columns, List<String> types) throws IOException{
	    bw.write("\t<!-- 通用查詢條件-->");
	    bw.newLine();
	    bw.write("\t<sql id=\"ParamSQL\">");
	    bw.newLine();
	
	    for (int k = 1; k < columns.size(); k++) {
	        String tempField = processField(columns.get(k));
	        bw.write("\t\t <if test=\"" + tempField + " != null and "+tempField+" !='' \">");
	        bw.newLine();
	        bw.write("\t\t\t AND " + columns.get(k) + " = #{" + tempField + "}");
	        bw.newLine();
	        bw.write("\t\t </if>");
	        bw.newLine();
	    }
	
	    bw.write("\t</sql>");
	    bw.newLine();
	    bw.newLine();
    }
    
    /**
     * 說明: 查詢(根據主鍵ID查詢)<br>
     * 創 建 人: hhl
     * @param bw
     * @param columns
     * @param types
     * @throws IOException
     */
    public static void selectByPrimaryKey(BufferedWriter bw, List<String> columns, List<String> types) throws IOException{
    	bw.write("\t<!-- 查詢(根據主鍵ID查詢) -->");
        bw.newLine();
        bw.write("\t<select id=\"selectByPrimaryKey\" parameterType=\"java.lang." + processType(types.get(0)) + "\" resultMap=\"" + processResultMapId(beanName) + "ResultMap\" >");
        bw.newLine();
        bw.write("\t\t SELECT");
        bw.newLine();
        bw.write("\t\t\t <include refid=\"Base_Column_List\" />");
        bw.newLine();
        bw.write("\t\t FROM " + tableName);
        bw.newLine();
        bw.write("\t\t WHERE " + columns.get(0) + " = #{" + processField(columns.get(0)) + "}");
        bw.newLine();
        bw.write("\t</select>");
        bw.newLine();
        bw.newLine();
    }
    
    /**
     * 說明: 查詢(根據條件查詢列表)<br>
     * 創 建 人: hhl
     * @param bw
     * @param columns
     * @param types
     * @throws IOException
     */
    public static void selectListByParam(BufferedWriter bw, List<String> columns, List<String> types) throws IOException{
    	 bw.write("\t<!-- 查詢(根據條件查詢列表) -->");
         bw.newLine();
         bw.write("\t<select id=\"selectListByParam\" parameterType=\"" + bean_package + "." + beanName + "\" resultMap=\"" + processResultMapId(beanName) + "ResultMap\">");
         bw.newLine();
         bw.write("\t\t SELECT");
         bw.newLine();
         bw.write("\t\t\t <include refid=\"Base_Column_List\" />");
         bw.newLine();
         bw.write("\t\t FROM " + tableName);
         bw.newLine();
         bw.write("\t\t <where>");
         bw.newLine();
         bw.write("\t\t\t <include refid=\"ParamSQL\" />");
         bw.newLine();
         bw.write("\t\t</where>");
         bw.newLine();
         bw.write("\t</select>");
         bw.newLine();
         bw.newLine();
    }
    
    /**
     * 說明: 刪除:根據主鍵ID刪除<br>
     * 創 建 人: hhl
     * @param bw
     * @param columns
     * @param types
     * @throws IOException
     */
    public static void deleteByPrimaryKey(BufferedWriter bw, List<String> columns, List<String> types) throws IOException{
    	 bw.write("\t<!--刪除:根據主鍵ID刪除-->");
         bw.newLine();
         bw.write("\t<delete id=\"deleteByPrimaryKey\" parameterType=\"java.lang." + processType(types.get(0)) + "\">");
         bw.newLine();
         bw.write("\t\t DELETE FROM " + tableName);
         bw.newLine();
         bw.write("\t\t WHERE " + columns.get(0) + " = #{" + processField(columns.get(0)) + "}");
         bw.newLine();
         bw.write("\t</delete>");
         bw.newLine();
         bw.newLine();
    }
    
    /**
     * Description: 新增 <br>
     * 創 建 人: hhl
     * 創建日期:2019年2月15日 下午2:20:18
     * @param bw
     * @param columns
     * @param types
     * @throws IOException
     */
    public static void insert(BufferedWriter bw, List<String> columns, List<String> types) throws IOException{
    	 bw.write("\t<!-- 添加 (匹配有值的字段)-->");
         bw.newLine();
         bw.write("\t<insert id=\"insert\" parameterType=\"" + bean_package + "." + beanName + "\">");
         bw.newLine();
         bw.write("\t\t INSERT INTO " + tableName);
         bw.newLine();
         bw.write("\t\t <trim prefix=\"(\" suffix=\")\" suffixOverrides=\",\" >");
         bw.newLine();

         String tempField;
         for (String column : columns) {
             tempField = processField(column);
             bw.write("\t\t\t<if test=\"" + tempField + " != null and "+tempField+" !='' \">");
             bw.write(column + ",");
             bw.write("</if>");
             bw.newLine();
         }

         bw.write("\t\t </trim>");
         bw.newLine();

         bw.write("\t\t <trim prefix=\"values (\" suffix=\")\" suffixOverrides=\",\" >");
         bw.newLine();

         for (String column : columns) {
             tempField = processField(column);
             bw.write("\t\t\t<if test=\"" + tempField + " != null and "+tempField+" !='' \">");
             bw.write(" #{" + tempField + "},");
             bw.write("</if>");
             bw.newLine();
         }

         bw.write("\t\t </trim>");
         bw.newLine();
         bw.write("\t</insert>");
         bw.newLine();
         bw.newLine();
    }
    
    /**
     * Description: 修改<br>
     * 創 建 人: hhl
     * 創建日期:2019年2月15日 下午2:23:17
     * @param bw
     * @param columns
     * @param types
     * @throws IOException
     */
    public static void update(BufferedWriter bw, List<String> columns, List<String> types) throws IOException{
    	bw.write("\t<!-- 修 改-->");
        bw.newLine();
        bw.write("\t<update id=\"update\" parameterType=\"" + bean_package + "." + beanName + "\">");
        bw.newLine();
        bw.write("\t\t UPDATE " + tableName);
        bw.newLine();
        bw.write("\t\t <trim prefix=\"set\" suffixOverrides=\",\">");
        bw.newLine();

        String tempField;
        for (int i = 1; i < columns.size(); i++) {
            tempField = processField(columns.get(i));
            bw.write("\t\t\t<if test=\"" + tempField + " != null and "+tempField+" !='' \">");
            bw.write(columns.get(i) + " = #{" + tempField + "},");
            bw.write("</if>");
            bw.newLine();
        }

        bw.write("\t\t</trim>");
        bw.newLine();
        bw.write("\t\t WHERE " + columns.get(0) + " = #{" + processField(columns.get(0)) + "}");
        bw.newLine();
        bw.write("\t</update>");
        bw.newLine();
        bw.newLine();
    }

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章