Spring启动Mybatis动态查询

Spring Boot Mybatis Dynamic query

你好,我是 mybatis 的新手,也是我第一次尝试在 spring 引导中使用注释。

我的代码是这样的:

@Select("<script>"
            + "SELECT t.something, s.somewhat, "
            + "FROM t.table1 t "
            + "LEFT JOIN table2 s ON t.id = s.id "
            + "WHERE s.delete_date IS NULL "
            + "<if test=\"isnew\"> "
            + "AND t.insert_date = t.update_date "
            + "AND (t.score >= s.min_score AND t.score <= s.max_score) "
            + "</if>"
            + "union "
            + "ANOTHER SIMILAR QUERY WITH ANOTHER <IF> + "</script>")
List<Map<String, Object>> methodName(@Param("isnew") Boolean isNew);

这是错误。

Caused by: java.lang.IllegalArgumentException: org.apache.ibatis.builder.BuilderException: Could not find value method on SQL annotation. Cause: org.apache.ibatis.builder.BuilderException: Error creating document instance. Cause: org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 822;

我几乎可以肯定存在非常可预测的语法错误,但我找不到它。 以下是我尝试过的一些示例,其中 none 个有效:

提前致谢

对于可能遇到相同问题的人,这是解决方案:

你必须转义字符 < ,因为 mybatis 将其视为未打开的标记, < 将起作用:

            + "SELECT t.something, s.somewhat, "
            + "FROM t.table1 t "
            + "LEFT JOIN table2 s ON t.id = s.id "
            + "WHERE s.delete_date IS NULL "
            + "<if test=\"isnew\"> "
            + "AND t.insert_date = t.update_date "
            + "AND (t.score >= s.min_score AND t.score lt;= s.max_score) "
            + "</if>"
            + "union "
            + "ANOTHER SIMILAR QUERY WITH ANOTHER <IF> + "</script>")
List<Map<String, Object>> methodName(@Param("isnew") Boolean isNew);```