如何基于枚举常量参数在myBatis 3.1.1中执行动态SQL?
答案 0 :(得分:15)
如何基于枚举常量执行动态SQL
public enum Test {
A, B;
}
Mapper.java:
int test(@Param("t") Test t);
Mapper.xml:
<select id="test" resultType="int">
select
<choose>
<when test='t.name().equals("A")'>65</when>
<when test='t.name().equals("B")'>66</when>
<otherwise>0</otherwise>
</choose>
</select>
备注强>
答案 1 :(得分:4)
对于==
(或equals
)语句中的字符串,MyBatis允许if
代替when
。所以以下内容也适用(引用并不重要):
public enum Test {
A, B;
}
Mapper.java:
int test(@Param("t") Test t);
Mapper.xml:
<select id="test" resultType="int">
select
<choose>
<when test="t.name() == 'A'">65</when>
<when test="t.name() == 'B'">66</when>
<otherwise>0</otherwise>
</choose>
</select>
答案 2 :(得分:1)
除了Tomer的答案,它的工作正常,您还可以使用OGNL表示法比较枚举值。
(比较枚举值直接具有编译时优势,即,如果更改枚举成员,查询将快速失败。)
如果Test enum在full.package.name中作为公共类,Test.java,则在mapper.xml中,你有:
<when test='t == @full.package.name.Test@A'>
如果Test enum在另一个类中,如下所示:
package full.package.name;
public class ExampleClass {
public enum Test {
A, B
}
}
然后,在mapper.xml中你有:
<when test='t == @full.package.name.ExampleClass$Test@A'>
$符号在OGNL规范中没有记录,我已经找到了 in the MyBatis issues page
PS:如果OGNL字符串不正确(例如,NullPointerException),旧版本的MyBatis(例如,3.2.3)会显示丑陋的错误。较新的版本显示更容易理解的错误。
答案 3 :(得分:0)
public enum Test {
A, B;
}
Mapper.java:
int test(@Param("t") Test t);
Mapper.xml:
<select id="test" resultType="int">
select
<choose>
**<when test='t.name() == "A"'>65</when>
<when test='t.name() == "A"'>66</when>**
<otherwise>0</otherwise>
</choose>
</select>
is another solution.