jdbi 版本 3,stringtemplate 何时转义 <, > 字符?

jdbi version 3, stringtemplate when to escape <, > characters?

我正在使用 jdbi3 和 StringTemplate 4 模板引擎,我有这个测试查询:

    @SqlQuery("select * from test "
        + "where field1 = 5"
        + "<if(cond1)> or field2 \<= :value1<endif>"
        + "<if(cond2)> or field2 >= :value2<endif>"
        + "<if(cond3)> or field2 in (<values>)<endif>")
@RegisterBeanMapper(Test.class)
@UseStringTemplateEngine
public List<Test> selectTest(
        @Define("cond1") boolean cond1, @Bind("value1") int value2,
        @Define("cond2") boolean cond2, @Bind("value2") int value3,
        @Define("cond3") boolean cond3,
        @BindList(value="values", onEmpty=BindList.EmptyHandling.NULL_STRING ) List<Integer> values);

当我必须在查询中使用 \ 字符 <> 转义时使用 StringTemplate 引擎? 测试我发现我必须像以前一样在查询中转义 <=

在使用 @BindList 的 IN 子句中,我必须使用 <values> 但在这种情况下,我希望像 \<values> 那样转义它,否则它将被 StringTemplate 用作属性但如果我这样做,查询将不起作用。

关于 >= 转义与否在查询中似乎是一样的。

简介

让我们考虑一下:

  • 3.27.1 Jdbi 版本为当前 Jdbi 版本。
  • 4.3.1 StringTemplate 版本作为当前 StringTemplate 版本,因为当前 Jdbi 版本使用它。请参阅:jdbi/pom.xml at v3.27.1 · jdbi/jdbi.

回答

Jdbi

文档:要转义的字符

请注意要转义哪些字符的警告:

Since StringTemplate by default uses the < character to mark ST expressions, you might need to escape some SQL: String datePredSql = "<if(datePredicate)> <dateColumn> \< :dateFilter <endif>"

jdbi/index.adoc at v3.27.1 · jdbi/jdbi.

Unit-test:不转义@BindList变量名

请参阅BindListTest.ifValueGivenWithNullValueOptionThenResultIsTruthy()测试方法:jdbi/BindListTest.java at v3.27.1 · jdbi/jdbi

请注意,该测试涵盖了一个非常相似的注释方法:

@SqlQuery("select name from something <if(name)> where name in (<name>) <endif>")
@UseStringTemplateEngine
List<String> getForValue(@Nonnull @BindList(value = "name", onEmpty = NULL_VALUE) List<String> name);

请注意,@BindList 变量名未转义:

in (<name>)

字符串模板

文档:要转义的字符

请注意要转义的字符:

A template is a sequence of text and expression elements, optionally interspersed with comments. At the coarsest level, the basic elements are:

text
<expr>
<! comment !>

Escape delimiters with a backslash character: \< or \>.

stringtemplate4/templates.md at 4.3.1 · antlr/stringtemplate4.