Using enum parameters in myBatis dynamic SQL

Tomer picture Tomer · Oct 17, 2012 · Viewed 12.5k times · Source

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

Answer

Tomer picture Tomer · Oct 17, 2012

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.