Enum constant in sql query mybatis

I need to specify the enum constant in the request. I tried the following example

<select=...>
  select * from tableA where value = @MyEnum@Value.tostring()
</select>

but it just inserts the value @MyEnum@Value.tostring(). Also i tried

#{@MyEnum@Value.tostring()}

but it is considered as a query parameter. So how can I use the enum constant in a query?

Column PS - varchar

+3
source share
3 answers

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

Listed listing:

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
    }
}

If you want to use any attribute of your listing.

Then you should use this form in the xml file:

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

MyBatis enters a value without quotes, so you must enclose it in quotation marks.

Tested by MyBatis 3.3.1

+4
source

, Java MyBatis? , @MyEnum@.

, , MyBatis, Java ( , MyBatis.NET .) MyBatis-3.1.1

<select id="getSomeObjectByValue" resultType="SomeObject" parameterType="MyEnum">
  SELECT *
  FROM tableA
  WHERE UPPER(value) = #{param1.toString()}
</select>

"param1" - , MyBatis ( ), , , :/p >

<select id="getSomeObjectByValue" resultType="SomeObject">
  SELECT *
  FROM tableA
  WHERE UPPER(value) = #{p.toString()}
</select>

, Type, .

+1

Rating Only:

If you want to use it in <if test = "..."> you can also do the following:

<if test="enumParam == @the.enum.pack.MyEnum@VALUE">
    ...
</if>

And it works great.

0
source

All Articles