Using enumeration options in myBatis dynamic SQL

How to make dynamic SQL in myBatis 3.1.1 based on enum constant parameter?

+7
source share
4 answers

How to make dynamic SQL based on enum constants

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> 

Notes

  • The test expression must refer to strings using double quotes, not single quotes.
  • You cannot compare constants, only strings.
+12
source

MyBatis allows == instead of equals for strings in if (or when ) operations. So the following will also work (citations don't matter):

 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
source
 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() == &quot;A&quot;'>65</when> <when test='t.name() == &quot;A&quot;'>66</when>** <otherwise>0</otherwise> </choose> </select> is another solution. 
0
source

Besides the Tomer answer, which works fine, you can also compare enum values ​​using OGNL notation.

(Comparing enumeration values ​​directly has the advantage of compiling, i.e. if you change the members of an enumeration, the query will work quickly.)

If the test enumeration lives in full.package.name as an open class Test.java, then in mapper.xml you will have:

 <when test='t == @ full.package.name.Test@A '> 

If the test enum is inside another class, for example:

 package full.package.name; public class ExampleClass { public enum Test { A, B } } 

Then in the mapper.xml file you will have:

 <when test='t == @ full.package.name.ExampleClass$Test@A '> 

The $ sign is not documented in the OGNL spec, I found it on the MyBatis problems page

PS: Old versions of MyBatis (e.g. 3.2.3) show ugly errors if the OGNL string is incorrect (e.g. NullPointerException). Newer versions show a more understandable error.

0
source

All Articles