3
5

More than 3 years have passed since last update.

MyBatisのMapper XMLでJavaの列挙型(Enum)を使う方法

Posted at

はじめに

MyBatisのMapper XMLにおいて、
ネット上に定数(static final)を参照するコードはあるものの、
列挙型(enum)を参照するコードはあまり見かけなかったので記事にしました。

インストール

build.gradle
    compile 'org.mybatis:mybatis:3.5.2'

列挙型サンプル

SampleEnums.java
package com.example;

public class SampleEnums {

    public enum Color {
        RED("1"), GREEN("2"), BLUE("3");

        private final String code;

        private Color(final String code) {
            this.code = code;
        }

        public String getCode() {
            return this.code;
        }
    }
}

Mapper XMLサンプル(コードを設定)

<select id="findByColorIsBlue" resultType="SampleDto">
    SELECT *
      FROM SAMPLE_TABLE
     WHERE COLOR = '${@com.example.SampleEnums$Color@BLUE.getCode}'

<!-- 生成されるSQL
    SELECT *
      FROM SAMPLE_TABLE
     WHERE COLOR = '2'
-->
</select>

Mapper XMLサンプル2(名称を設定)

<select id="findByColorIsBlue" resultType="SampleDto">
    SELECT *
      FROM SAMPLE_TABLE
     WHERE COLOR = '${@com.example.SampleEnums$Color@BLUE}'

<!-- 生成されるSQL
    SELECT *
      FROM SAMPLE_TABLE
     WHERE COLOR = 'BLUE'
-->
</select>
3
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
5