美文网首页
mybatis的xml中不写if 使用代码拼接

mybatis的xml中不写if 使用代码拼接

作者: 淹死丶的鱼 | 来源:发表于2021-04-28 18:22 被阅读0次

    在mybatis中的xml写sql的时候如果查询的条件非常多就会多出很多行的代码
    这里介绍一下我的想法,最近想到的,实践了一下是可行的,和xml的if拼接是一样的

    使用javapot实现动态拼接代码

    1. 读取文件
     public static String root = "com.finish.mp.";
        public static String boPackage = "t1.bo";
        public static String enumPath = "com.finish.mp.sysenum";
    
        @Test
        public void autoQueryPage() throws Exception {
            File file = new File(T2.class.getResource("/").getPath());
            String parent = new File(file.getParent()).getParent();
            String rootPath = parent + "\\src\\main\\java\\" + root.replace(".", "\\");
            File[] fileBO = new File(rootPath + boPackage.replace(".", "\\")).listFiles();
    
            TypeSpec.Builder classSpec = TypeSpec.classBuilder("Page2Sql")
                    .addModifiers(Modifier.PUBLIC);
            List<String> collect = Arrays.stream(fileBO).map(file1 -> file1.getName().split("\\.")[0]).collect(Collectors.toList());
            for (String s : collect) {
                Class<?> bo = Class.forName(root + boPackage + "." + s);
                MethodSpec bo2sql = createMethod(bo);
                classSpec.addMethod(bo2sql);
            }
            TypeSpec build = classSpec.build();
            File file1 = new File(rootPath + "\\utils");
            if (!file1.exists()) {
                file1.mkdirs();
            }
            JavaFile.builder("", build).build().writeTo(file1);
    
        }
    
    1. 编写注解 划线的不是这个里面的


      image.png
    2. 在指定的字段使用注解


      image.png
    3. 编写生成方法的javapot代码 这里的dr是逻辑删除
             private MethodSpec createMethod(Class<?> bo) throws Exception {
            String boName = toLowerCaseFirstOne(bo.getSimpleName());
            StringBuilder s = new StringBuilder(boName);
            boName = s.delete(s.length() - 2, s.length()).toString();
            MethodSpec.Builder builder = MethodSpec.methodBuilder(toLowerCaseFirstOne(boName) + "2Sql")
                    .addParameter(ParameterSpec.builder(bo, boName).build())
                    .returns(String.class)
                    .addModifiers(Modifier.PUBLIC, Modifier.STATIC);
            builder.addStatement("StringBuilder st = new StringBuilder()");
            builder.addStatement("st.append(\"where t.dr = 0\")");
            Field[] fields1 = bo.getSuperclass().getDeclaredFields();
            Field[] fields2 = bo.getDeclaredFields();
    
            List<Field> fields = new ArrayList<>();
            fields.addAll(Arrays.asList(fields1));
            fields.addAll(Arrays.asList(fields2));
            for (Field field : fields) {
                field.setAccessible(true);
                TableField annotation = field.getAnnotation(TableField.class);
                Like like = field.getAnnotation(Like.class);
                LeftLike leftLike = field.getAnnotation(LeftLike.class);
                RightLike rightLike = field.getAnnotation(RightLike.class);
    //这里注解名字改了,就是大于小于和开闭区间的意思
                LessThan endTime = field.getAnnotation(LessThan.class);
                GreaterThan startTime = field.getAnnotation(GreaterThan.class);
                SqlIgnore sqlIgnore = field.getAnnotation(SqlIgnore.class);
                if (sqlIgnore != null) {
                    continue;
                }
                String name = field.getName();
                if (annotation != null) {
                    name = annotation.value();
                }
                String s1 = boName + ".get" + toUpperCaseFirstOne(field.getName());
                if (!field.getType().getName().contains(enumPath)) {
                    if (field.getType() == String.class) {
                        builder.addCode("if(" + s1 + "()!=null&&! \"\".equals(" + s1 + "())){");
                        if (like != null) {
                            builder.addStatement("st.append(\" and t." + name + " = \").append(\"'%\").append(" + s1 + "()).append(\"%'\")");
                        } else if (leftLike != null) {
                            builder.addStatement("st.append(\" and t." + name + " = \").append(\"'%\").append(" + s1 + "()).append(\"'\")");
                        } else if (rightLike != null) {
                            builder.addStatement("st.append(\" and t." + name + " = \").append(\"'\").append(" + s1 + "()).append(\"%'\")");
                        } else if (endTime != null) {
                            if (endTime.value() == 1) {
                                builder.addStatement("st.append(\" and t." + name + " < \").append(\"'\").append(" + s1 + "()).append(\"'\")");
                            } else {
                                builder.addStatement("st.append(\" and t." + name + " <= \").append(\"'\").append(" + s1 + "()).append(\"'\")");
                            }
                        } else if (startTime != null) {
                            if (startTime.value() == 1) {
                                builder.addStatement("st.append(\" and t." + name + " > \").append(\"'\").append(" + s1 + "()).append(\"'\")");
                            } else {
                                builder.addStatement("st.append(\" and t." + name + " >= \").append(\"'\").append(" + s1 + "()).append(\"'\")");
                            }
                        } else {
                            builder.addStatement("st.append(\" and t." + name + " = \").append(\"'\").append(" + s1 + "()).append(\"'\")");
                        }/* else {
                            builder.addStatement("st.append(\" and t." + name + " = \").append(\"'\").append(" + s1 + "()).append(\"%'\")");
                        }*/
                    } else if (field.getType().getName().contains("java")) {
                        builder.addCode("if(" + s1 + "()!=null){");
                        builder.addStatement("st.append(\" and t." + name + " = \").append(" + s1 + "())");
                    }
                } else {
                    builder.addCode("if(" + s1 + "()!=null){");
                    builder.addStatement("st.append(\" and t." + name + " = \").append(" + s1 + "().getIndex())");
                }
                builder.addCode("}");
            }
            builder.addStatement("return st.toString()");
    
            return builder.build();
        }
    
    1. 生成样例 这里没有加上包 手动加下


      image.png
    2. 代码实践


      image.png

    相关文章

      网友评论

          本文标题:mybatis的xml中不写if 使用代码拼接

          本文链接:https://www.haomeiwen.com/subject/qntbrltx.html