Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using enum parameters in myBatis dynamic SQL

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

like image 759
Tomer Avatar asked Oct 17 '12 11:10

Tomer


2 Answers

How to do 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 can't compare constants, only strings.
like image 122
Tomer Avatar answered Sep 18 '22 08:09

Tomer


MyBatis allows == instead of equals for strings in if (or when) statements. So the following would also work (quotes 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>
like image 20
Nailgun Avatar answered Sep 21 '22 08:09

Nailgun