maks
maks

Reputation: 6006

Enum constant in mybatis's sql query

I need to reference enum constant in query. I have tried next example

<select=...>
  select * from tableA where value = @[email protected]()
</select>

but it simply insert @[email protected]() value. Also I have tried

#{@[email protected]()}

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

PS value column is varchar

Upvotes: 4

Views: 8374

Answers (3)

Francisco M
Francisco M

Reputation: 193

Only an appreciation:

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

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

And works fine.

Upvotes: 0

Krzysztof Sudziarski
Krzysztof Sudziarski

Reputation: 61

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 = '${@[email protected]()}'
</select>

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

Tested with MyBatis 3.3.1

Upvotes: 6

quux00
quux00

Reputation: 14604

Are you sure you are asking a question about using Java with MyBatis? I'm not sure what the @MyEnum@ notation is.

In any case, here is how you do what you are asking with MyBatis using Java (I don't know if the MyBatis.NET version has another way to do it.) I have tested this with MyBatis-3.1.1:

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

"param1" is the default name of the first parameter passed to MyBatis (I think), but when there is only one parameter being passed in, you can give it a different name, so something like this will also work:

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

Notice that I could leave the parameterType off as well and it still works.

Upvotes: 1

Related Questions