LoginSignup
26
21

More than 5 years have passed since last update.

MyBatisのMapper XMLでJavaの定数を使う方法

Posted at

こんな感じのお店テーブルがあったとして、

CREATE TABLE Store {
    id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(255) NOT NULL,
    type TINYINT NOT NULL,
    ...
}

typeがJavaの定数で定義されている。

package foo.product.constant;

public class StoreType {
    public static final int SUPER_MARKET = 1;
    public static final int CONVENIENCE_STORE = 2;
    ...
}

このとき、コンビニのリストを取りたい場合のMapper XMLはこんな感じになるが、「type = 2」がマジックナンバーになっているのでよろしくない。

<select id="getConvenienceStoreList" resultType="Store">
    SELECT * FROM Store
    WHERE type = 2
    ORDER BY id
    LIMIT #{start}, #{limit}
</select>

MyBatisのMapper XMLはOGNLベースの式が書けるので、以下のようにすれば定数を指定できる。

<select id="getConvenienceStoreList" resultType ="Store">
    SELECT * FROM Store
    WHERE type = ${@foo.product.constant.StoreType@CONVENIENCE_STORE}
    ORDER BY id
    LIMIT #{start}, #{limit}
</select>

ちなみにOGNLのパースの動作確認はこんな感じで行うことができる。この場合、misc.FooクラスのFOO_INTの値が標準出力される。

import org.apache.ibatis.ognl.Ognl;
import org.apache.ibatis.ognl.OgnlContext;
import org.apache.ibatis.ognl.OgnlException;

public class OgnlParseSample {
    public static void main(String[] args) throws OgnlException {
        OgnlContext context = new OgnlContext();
        Object parseExpression = Ognl.parseExpression("@misc.Foo@FOO_INT");
        System.out.println(Ognl.getValue(parseExpression, context));
    }
}

参考資料

26
21
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
26
21