import java.util.Arrays; import java.util.List; public class GenerateColumns { public static final String DOT = "."; public static final String BLANK = " "; public static final String COMMA = ","; public static String originalColumns = "ID,EMP_NO,EMP_NAME,SALARY"; public static String newColumns = "E_ID,E_EMP_NO,E_EMP_NAME,E_SALARY"; public static void main(String[] args) { String sql = generateSql("emp", "e"); System.out.println(sql); String xmlStr = generateMyBatisXml(newColumns); System.out.println(xmlStr); } public static String generateMyBatisXml(String newColumns) { String xmlStr = ""; String[] newColumnArr = newColumns.split(","); List<String> newColumnList = Arrays.asList(newColumnArr); for(int i = 0; i < newColumnList.size(); i++) { String currentXmlStr = "<result column=\"" + newColumnList.get(i).toUpperCase() + "\"" + BLANK + "jdbcType=\"VARCHAR\"" + BLANK + "property=\"" + newColumnList.get(i).toUpperCase() + "\"/>" + "\r\n"; xmlStr += currentXmlStr; } return xmlStr; } public static String generateSql(String tableName, String tableAbbr){ String sql = "SELECT" + BLANK; String[] originalColumnArr = originalColumns.split(","); List<String> originalColumnList = Arrays.asList(originalColumnArr); String[] newColumnArr = newColumns.split(","); List<String> newColumnList = Arrays.asList(newColumnArr); if(originalColumnList.size() == newColumnList.size()) { for(int i = 0; i < originalColumnList.size(); i++) { sql += tableAbbr.toUpperCase() + DOT + originalColumnList.get(i).toUpperCase() + BLANK + newColumnList.get(i).toUpperCase() + COMMA; } sql = sql.substring(0, sql.length() - 1); sql += BLANK + "FROM" + BLANK + tableName.toUpperCase() + BLANK + tableAbbr.toUpperCase(); } return sql; } }
运行结果:
SELECT E.ID E_ID,E.EMP_NO E_EMP_NO,E.EMP_NAME E_EMP_NAME,E.SALARY E_SALARY FROM EMP E
<result column="E_ID" jdbcType="VARCHAR" property="E_ID"/>
<result column="E_EMP_NO" jdbcType="VARCHAR" property="E_EMP_NO"/>
<result column="E_EMP_NAME" jdbcType="VARCHAR" property="E_EMP_NAME"/>
<result column="E_SALARY" jdbcType="VARCHAR" property="E_SALARY"/>