MyBatisで下のようなSELECT文の結果を、用意したクラスにマッピングしたい
select user_id, user_name, hashed_password from some_table where id = #{id}
この方法について調べた
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 で指定することができる
デフォルトは未指定
まだ他にも機能があるけど、そのときにまた調べる