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の1対多のレコード取得についてのまとめ

Posted at

今回MyBatisの1対多のレコード取得について学習したので、備忘として残しておく。

前提
・テーブルはemployeesとattendancesの2つ。
・employeesが1でattendancesが多

テーブル構造
image.png

DTO

EmployeeE.java

package com.example.demo.entity;

import java.sql.Timestamp;
import java.util.List;

import lombok.Data;

/**
 * 従業員データのDTOモデル
 *
 */
@Data
public class EmployeeE {

	/**
	 * id
	 */
	private Integer id;

	/**
	 * 社員番号
	 */
	private String code;

	/**
	 * てすと
	 */
	private List<Attendance> attendances;

}

Attendance.java
package com.example.demo.entity;

import lombok.Data;

/**
 * 勤務データのDTOモデル
 *
 */
@Data
public class Attendance {

	/**
	 * id
	 */
    private Integer id;

	/**
	 * コメント
	 */
    private String content;

	/**
	 * 従業員id
	 */
    private Integer employeeId;

}

取得方法1 SQLを二つ発行して取得する方法

EmployeeMapper.xml

    <resultMap id="View_Result_Map" type="com.example.demo.entity.EmployeeE" >
        <collection
            property="attendances"
            ofType="com.example.demo.entity.Attendance"
            select="selectAttendancesByEmployeeId"
            column="id" />
    </resultMap>
 
    <select id="findAllE" resultMap="View_Result_Map">
        select *
        from Employees
    </select>

    <select id="selectAttendancesByEmployeeId" parameterType="int" resultType="com.example.demo.entity.Attendance">
        select *
        from Attendances
        where employee_id = #{id}
    </select>

所得方法2 テーブルを結合して一括で取得する方法

EmployeeMapper.xml

    <resultMap id="View2_Result_Map" type="com.example.demo.entity.EmployeeE" >
    		<result property="id" column="id" />
       		<result property="code" column="code" />

       <collection property="attendances"  ofType="com.example.demo.entity.Attendance" >
            <result property="content" column="content" />
       		<result property="employeeId" column="emoloyee_id" />

       </collection>

    </resultMap>

    <select id="findAllE2" resultMap="View2_Result_Map">
        select employees.id, employees.code, attendances.content, attendances.employee_id
        from employees
        left join attendances on employees.id = attendances.employee_id
    </select>

※resultmapのresultは指定する必要あり。
指定しないとnullになる。

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?