UGA Boxxx

つぶやきの延長のつもりで、知ったこと思ったこと書いてます

【MyBatics】結果のマッピング

MyBatisで下のようなSELECT文の結果を、用意したクラスにマッピングしたい

select
  user_id, user_name, hashed_password
  from some_table
  where id = #{id}

この方法について調べた

mybatis.org

Result Maps

Result Mapsを使うのが良さそう

こんな感じで使う

<select id="selectUsers" resultMap="userResultMap">
  select user_id, user_name, hashed_password
  from some_table
  where id = #{id}
</select>
<resultMap id="userResultMap" type="User">
  <id property="id" column="user_id" />
  <result property="username" column="username"/>
  <result property="password" column="password"/>
</resultMap>

わかりやすい

プロパティにコレクションを持つ場合

次のようにプロパティにコレクションを持つ場合

class User {
  private UUID id;
  private String type;
  private Set<UserName> names;
}
class UserName {
  private UUID id;
  private String name;
}

xmlファイルでは次のようにcollectionを使う

<select id="selectUsers" resultMap="userResultMap">
select
  user_id, user_type, user_name
  from some_table
  inner join name_table on some_table.id = name_table.id
  where user_id = #{id}
</select>
<resultMap id="userResultMap" type="User">
  <id property="id" column="user_id" />
   <collection property="names" ofType="UserName">
      <id column="user_id"/>
      <result column="name" property="name"/>
    </collection>
</resultMap>

autoMapping

プロパティがたくさんある時、わざわざxml内でそれらを列挙したくない

そんなときはautoMapping属性を使う

<resultMap id="userResultMap" type="User" autoMapping="true">

autoMappingは resulMap に結果をマッピングする際、自動マッピングを使用するかどうかを true / false で指定することができる

デフォルトは未指定

まだ他にも機能があるけど、そのときにまた調べる