ネストしたオブジェクトのマッピング
1対多の関係のマッピング
@Data
public class Student {
private String studentId;
private String roomId;
private String name;
private String age;
}
@Data
public class Teacher {
private String teacherId;
private String roomId;
private String name;
private String age;
private String subject;
}
@Data
public class ClassRoomDto {
private String teacherId;
private String roomId;
private Teacher teacher;
private List<Student> studentList;
}
マッパー
@Mapper
public interface PracticeDao {
List<ClassRoomDto> selectClassRoomList(@Param("teacherId") String teacherId);
}
xml
<resultMap id="BaseMap" type="com.example.practice.dto.ClassRoomDto">
<id column="TEACHER_ID" jdbcType="CHAR" property="teacherId" />
<id column="ROOM_ID" jdbcType="CHAR" property="roomId" />
<association property="teacher" javaType="com.example.practice.entity.Teacher">
<id column="TEACHER_ID" jdbcType="CHAR" property="teacherId" />
<id column="ROOM_ID" jdbcType="CHAR" property="roomId" />
<result column="NAME" jdbcType="CHAR" property="name" />
<result column="AGE" jdbcType="CHAR" property="age" />
<result column="SUBJECT" jdbcType="CHAR" property="subject" />
</association>
<collection property="studentList" ofType="com.example.practice.entity.Student">
<id column="STUDENT_ID" jdbcType="CHAR" property="studentId" />
<id column="ROOM_ID" jdbcType="CHAR" property="roomId" />
<result column="S_NAME" jdbcType="CHAR" property="name" />
<result column="S_AGE" jdbcType="CHAR" property="age"/>
</collection>
</resultMap>
<select id="selectClassRoomList" parameterType="map" resultMap="BaseMap">
SELECT
T.TEACHER_ID
, T.ROOM_ID
, T.NAME
, T.AGE
, T.SUBJECT
, S.STUDENT_ID
, S.ROOM_ID
, S.NAME AS S_NAME
, S.AGE AS S_AGE
FROM
TEACHER T
INNER JOIN
STUDENT S
ON T.ROOM_ID = S.ROOM_ID
WHERE
T.TEACHER_ID = #{teacherId, jdbcType=CHAR}
</select>
結果
[ClassRoomDto(teacherId=T001, roomId=A01,
teacher=Teacher(teacherId=T001, roomId=A01, name=田中 一郎, age=40, subject=数学),
studentList=[
Student(studentId=S001, roomId=A01, name=山田 太郎, age=15),
Student(studentId=S004, roomId=A01, name=佐藤 次郎, age=15),
Student(studentId=S005, roomId=A01, name=高橋 花子, age=14)])]