Bootstrap

mybatis中resultmap标签生成

最近在弄mybatis xml的时候,写resultmap因为类中字段比较多,cv到手发软

然后就想到写一个工具类直接生成

整个思路是通过反射获取到类的字段,然后拼接字符串,最后输出到控制台

大大的减少了写resultmap的cv次数,直接解放双手

工具类代码

/**
 * 生成resultMap
 * @author Sir丶忌尘
 */
public class ResUltMapUtil {

    public static void production(Class c){
        Field[] declaredFields = c.getDeclaredFields();
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("<resultMap id=\"");
        stringBuffer.append(c.getSimpleName());
        stringBuffer.append("\" type=\"");
        stringBuffer.append(c.getCanonicalName());
        stringBuffer.append("\">\n");
        for (Field declaredField : declaredFields) {
            if (declaredField.isAnnotationPresent(TableField.class)){
                TableField annotation = declaredField.getAnnotation(TableField.class);
                if (!annotation.exist()){
                    continue;
                }
            }
            if ("id".equals(declaredField.getName())){
                stringBuffer.append("<id column=\"");
            } else if ("serialVersionUID".equals(declaredField.getName())) {
                continue;
            } else {
                stringBuffer.append("<result column=\"");
            }

            stringBuffer.append(humpToLine(declaredField.getName()));
            stringBuffer.append("\" property=\"");
            stringBuffer.append(declaredField.getName());
            stringBuffer.append("\"/>\n");
        }
        stringBuffer.append("</resultMap>");
        System.out.println(stringBuffer);
    }

  
    public static String humpToLine(String str) {
        Matcher matcher = Pattern.compile("[A-Z]").matcher(str);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, "_" + matcher.group(0).toLowerCase());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }

    public static void main(String[] args) {
        production(Dome.class);
    }

}

测试Dome类

@Data
public class Dome {
    private Integer id;
    private String userName;
    private Integer age;
}

运行main方法,生成的resultmap标签

;