MyBatis | 検索結果を任意のJavaオブジェクトにマッピング | カラム名に接頭辞(prefix)を指定する

データテーブル

foo_table

id bar_id
1 3
2 2
3 1

bar_table

id
1
2
3

ソースコード

Foo.java

package sample.mybatis;

public class Foo {
    private int id;
    private Bar bar;

    @Override
    public String toString() {
        return "Foo [id=" + id + ", bar=" + bar + "]";
    }
}

Bar.java

package sample.mybatis;

public class Bar {
    private int id;

    @Override
    public String toString() {
        return "Bar [id=" + id + "]";
    }
}

sample_mapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="sample.mybatis">

  <resultMap type="sample.mybatis.Foo" id="fooResultMap">
    <id property="id" column="id" />
    <!-- columnPrefixで共通の接頭辞を指定する。 -->
    <association property="bar" columnPrefix="bar_" resultMap="barResultMap" />
  </resultMap>

  <resultMap type="sample.mybatis.Bar" id="barResultMap">
    <id property="id" column="id" />
  </resultMap>

  <select id="selectFoo" resultMap="fooResultMap">
    select foo.id
          ,bar.id bar_id -- "bar_"を接頭辞として指定
      from foo_table foo
          ,bar_table bar
     where bar.id = foo.bar_id
  order by foo.id asc
  </select>
</mapper>

selectFooの実行結果

Foo [id=1, bar=Bar [id=3]]
Foo [id=2, bar=Bar [id=2]]
Foo [id=3, bar=Bar [id=1]]

説明

  • JOINを行うとき、他のテーブルの同名カラムと区別するために、通常は接頭辞(bar_)を付けることになる。
  • そのような場合でもresultMapを使用できるように、columnPrefixという属性が用意されている。
  • columnPrefixを指定すると、columnの設定値に接頭辞を付けた名前でマッピングが行われる。