Enum constant in mybatis's sql query

java, mybatis, sql

Solution

If you want to access any enum constant in MyBatis you should use this form:

Given enum:

package org.sample.domain;

public enum Currency {
    USD("$"), YEN("Y"), PLN("zl");

    private String symbol;

    Currency(String symbol) {
        this.symbol = symbol;
    }

    public String getSymbol() {
        return this.symbol
    }
}

When you want to use any attribute of your enum.

Then you have to use this form in you xml file:

<select id="report" resultMap="resultMap">
    SELECT *
    FROM invoices
    WHERE currency_symbol = '${@org.sample.domain.Currency@USD.getSymbol()}'
</select>

MyBatis is injecting value without any quotes therefore you have to enclose it in quotes.

Tested with MyBatis 3.3.1

Problem

I need to reference enum constant in query. I have tried next example ``` <select=...> select * from tableA where value = @MyEnum@Value.tostring() </select> ``` but it simply insert `@MyEnum@Value.tostring()` value. Also I have tried ``` #{@MyEnum@Value.tostring()} ``` but it is treated as query parameter. So how can I use enum constant in query? PS value column is varchar

Original source