ネストしたオブジェクトでAutoMappingを使う #mybatis

MybatisのネストしたresultMapの自動マッピングはデフォルトPARTIALになっている。

つまり、ネストしたオブジェクトのauto-mappingは効かないということ。

これだといちいちマッピングを定義してやらなきゃいけないのでとてもつらいのだが、設定を変えなくても、個別にresltMapを定義してやることで、auto-mappingを使える。

対象のマッパークラス

public class Company {
  private long id;
  private String name;
  private List<Section> sections; // 部署リスト

  // アクセサは省略
}

public class Section {
  private long id;
  private String name;
  private Member representative; // 代表者

  // アクセサは省略
}

public class Member {
  private long id;
  private String name;

  // アクセサは省略
}

SQLのイメージ

SELECT
    company.id    AS id
  , company.name  AS name
  , section.id    AS section_id
  , section.name  AS section_name
  , member.id     AS representative_id
  , member.name   AS representative_name
FROM
  company
  inner join
  section
    on company.id = section.company_id
  inner join
  member
    on section.representative_id = member.id

これはNG

<resultMap id="companyMap" autoMapping="true" type="Company">
    <id property="id" column="id"/>
    <collection property="sections" autoMapping="true" columnPrefix="section_" ofType="Section">
        <id property="id" column="id"/>
        <association property="representative" columnPrefix="representative_" javaType="Member" autoMapping="true">
            <id property="id" column="id"/>
        </association>
    </collection>
</resultMap>

これはOK

<resultMap id="companyMap" autoMapping="true" type="Company">
    <id property="id" column="id"/>
    <collection property="sections" autoMapping="true" columnPrefix="section_" ofType="Section">
        <id property="id" column="id"/>
        <association property="representative" columnPrefix="representative_" resultMap="memberMap">
    </collection>
</resultMap>
<resultMap id="memberMap" type="Member" autoMapping="true">
    <id property="id" column="id"/>
</resultMap>

SQLと紐付け

<select id="getCompany" resultMap="companyMap">
  <!-- ここにSQLを書く -->
</select>

参考