0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

MyBatisでコレクションを返す

Last updated at Posted at 2023-11-07

MyBatisでは親子関係のテーブルのレコードをマッピングによって取得することができます。

POJO

Javaでは以下のように子テーブルをネストしたPOJOを用意しておきます。

public class MainJoho implements Serializable {

	private String mainId;

	private String mainName;

	private List<SubJoho> subJohoList;
}
public class SubJoho {

	private String subId;

	private String subName;

 	private String subType;
}

Mapper

Mapperではcollectionを使ってネストした子テーブルをマッピングできるようにします。

  <resultMap id="MainJohoResultMap" type="jp.co.hoge.pojo.MainJoho">
    <result column="MAIN_ID" jdbcType="VARCHAR" property="mainId" />
    <result column="MAIN_NAME" jdbcType="VARCHAR" property="mainName" />
    <collection ofType="jp.co.hoge.pojo.SubJoho" property="subJohoList">
       <result column="SUB_ID" property="subId" />
       <result column="SUB_NAME" property="subName" />
       <result column="SUB_TYPE" property="subType" />
     </collection>
  </resultMap>
  <select id="selectList" resultMap="MainJohoResultMap">
    SELECT
    M_MAIN.MAIN_ID
    , MAIN_NAME
    , SUB_ID
    , SUB_NAME
    , SUB_TYPE
    FROM M_MAIN
    LEFT JOIN M_SUB
    ON M_MAIN.MAIN_ID = M_SUB.MAIN_ID
  </select>
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?