Mybatis注解一键转为xml文件


前言

提示:因规范需将使用注解形式完成编码的Mapper文件转为xml形式


提示:以下是本篇文章正文内容,下面案例可供参考

一、描述

运行测试后,将在resources\mapper下生成对应的.xml.generate并注释原文

二、代码

package com.cmcc.dao;

import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;

/**
 * @Author : LiuXin
 * @create 2023/2/9 16:07
 * @describe:
 * 将注解形式的sql转为xml,将已完成的Mapper层或者Dao注入当然test,在resources\mapper下生成对应的.xml.generate并对原文注释
 * 需要注意的是:
 *  1.注解形式的sql需写在一行,本代码没有对换行符和分隔符判断
 *  2.经测试,当返回集为List<Map>时,需要手动将返回的生成的ava.util.List转为java.util.Map
 *  3.只对@Select和@Update进行了解析,对于@Insert和@Delete并没有进行解析
 */
@SpringBootTest
public class GenerateXMLByAnnotationTest {

    @Resource
    private EquipmentDao equipmentDao;

    @Resource
    private EquipmentManageDao equipmentManageDao;

    @Resource
    private IpSubnetsdhcpDao ipSubnetsdhcpDao;

    @Resource
    private TelemetryDao telemetryDao;

    @Resource
    private TwampDao twampDao;

    private static final  String RESOURCE = "javax.annotation.Resource";

    private static final  String AUTOWIRED = "org.springframework.beans.factory.annotation.Autowired";

    private static final  String SELECT = "org.apache.ibatis.annotations.Select";

    private static final  String UPDATE = "org.apache.ibatis.annotations.Update";

    private static final  String INSERT = "org.apache.ibatis.annotations.Insert";

    private static final  String DELETE = "org.apache.ibatis.annotations.Delete";

    private static final  String PREFIX = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
            "<!DOCTYPE mapper PUBLIC \"-//mybatis.org//DTD Mapper 3.0//EN\" \"http://mybatis.org/dtd/mybatis-3-mapper.dtd\">\n" +
            "<mapper namespace=\""
            ;

    private static final  String INFIX = "\">";
    private static final  String SUFFIX = "</mapper>";
    private static final  String ENT = "\n";
    private static final  String FILE_SUFFIX = ".xml.generate";
    private static final  String JAVA_SUFFIX = ".java";
    private static final  String SUFFIX_PATH = "."+ File.separator+"src"+File.separator+"main"+File.separator+"resources"+File.separator+"mapper"+File.separator;
    private static final  String PATH = "."+File.separator+"src"+File.separator+"main"+File.separator+"java"+File.separator;


    @Test
    public void generate() throws ClassNotFoundException {
        Field[] declaredFields = this.getClass().getDeclaredFields();
        for (Field declaredField : declaredFields) {
            for (Annotation annotation : declaredField.getAnnotations()) {
                if(RESOURCE.equals(annotation.annotationType().getName()) || AUTOWIRED.equals(annotation.annotationType().getName())){
                    Class<?> DaoInterface = Class.forName(declaredField.getType().getName());
                    StringBuilder sb = new StringBuilder();
                    sb.append(PREFIX);
                    sb.append(DaoInterface.getName());
                    sb.append(INFIX);
                    for (Method declaredMethod : DaoInterface.getDeclaredMethods()) {
                        for (Annotation declaredAnnotation : declaredMethod.getDeclaredAnnotations()) {
                            switch (declaredAnnotation.annotationType().getName()){
                                case SELECT:{
                                    sb.append(ENT);
                                    sb.append("<select id=\"");
                                    sb.append(declaredMethod.getName());
                                    sb.append("\" resultType=\"");
                                    sb.append(declaredMethod.getReturnType().getTypeName());
                                    sb.append(INFIX);
                                    sb.append(ENT);
                                    Select select = (Select) declaredAnnotation;
                                    String sql = String.valueOf(Arrays.asList(select.value()));
                                    sql = removeChar(sql);
                                    sb.append(sql);
                                    sb.append(ENT);
                                    sb.append("</select>");
                                    sb.append(ENT);
                                    this.notesJava(DaoInterface.getName(), select);
                                    break;
                                }
                                case UPDATE:{
                                    sb.append(ENT);
                                    Update update = (Update) declaredAnnotation;
                                    sb.append("<update id=\"");
                                    sb.append(declaredMethod.getName());
                                    sb.append("\" parameterType=\"");
                                    if (declaredMethod.getGenericParameterTypes().length > 0){
                                        sb.append(declaredMethod.getParameterTypes()[0].getName());
                                    }
                                    sb.append(INFIX);
                                    sb.append(ENT);
                                    String sql = String.valueOf(Arrays.asList(update.value()));
                                    sql = removeChar(sql);
                                    sb.append(ENT);
                                    sb.append(sql);
                                    sb.append(ENT);
                                    sb.append("</update>");
                                    sb.append(ENT);
                                    this.notesJava(DaoInterface.getName(),update);
                                    break;
                                }
                            }

                        }
                    }
                    sb.append(SUFFIX);
                    this.generateXML(SUFFIX_PATH+DaoInterface.getSimpleName()+FILE_SUFFIX,sb.toString());
                }
            }
        }
    }

    private void notesJava(String name, Annotation annotation) {
        switch (annotation.annotationType().getName()){
            case SELECT:{
                Select s = (Select) annotation;
                String str = removeFlag(Arrays.toString(s.value()));
                this.notesJavaCode(name,str);
                break;
            }
            case UPDATE:{
                Update u = (Update) annotation;
                String str = removeFlag(Arrays.toString(u.value()));
                this.notesJavaCode(name,str);
                break;
            }

        }

    }

    private void notesJavaCode(String name, String str) {
        StringBuffer buffer = new StringBuffer();
        StringBuffer ctx = new StringBuffer();
        Arrays.asList(name.split("\\.")).forEach(s -> {
            buffer.append(s);
            buffer.append(File.separator);
        });
        StringBuffer at = buffer.deleteCharAt(buffer.length()-1);
        String path = PATH+at+JAVA_SUFFIX;

        try {
            List<String> allLines = Files.readAllLines(Paths.get(path));
            for (String line : allLines) {
                if (line.replaceAll("\\\\","").contains(str)){
                    ctx.append("//"+line+"\n");
                }else {
                    ctx.append(line+"\n");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        this.generateXML(path,ctx.toString());
    }

    //去除foreach的label
    private String removeChar(String sql){
        if (sql.startsWith("[")){
            sql  = sql.substring(1,sql.length());
        }
        if (sql.endsWith("]")){
            sql = sql.substring(0,sql.length()-1);
        }
        if (sql.startsWith("<script>")) {
            sql = sql.replace("<script>", "");
        }
        if (sql.endsWith("</script>")) {
            sql = sql.replace("</script>", "");
        }
        return sql;
    }
    private String removeFlag(String sql){
        if (sql.startsWith("[")){
            sql  = sql.substring(1,sql.length());
        }
        if (sql.endsWith("]")){
            sql = sql.substring(0,sql.length()-1);
        }
        return sql;
    }

    private void generateXML(String filePath,String content){
        FileWriter fw = null;
        try
        {
            File file = new File(filePath);
            if (!file.exists())
            {
                file.createNewFile();
            }
            fw = new FileWriter(filePath);
            fw.write(content);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            try
            {
                fw.close();
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }

        }
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值