Spring(boot)

Mybatis resultMap의 Collection 활용하기

p.guns23 2024. 11. 26. 16:07

들어가기 

2024.05.24 - [Spring(boot)] - [Spring Boot] Mybatis 연동하기

 

[Spring Boot] Mybatis 연동하기

안녕하세요! 😁😁이번에는 Spring Boot 프로젝트에 MyBatis를 연동하는 방법에 대해 진행하고자 합니다. MyBatis란?Mybatis는 자바 언어용 오픈 소스 퍼시스턴스 프레임워크입니다.데이터베이스와 자

guns23.tistory.com

지난번에 springBoot와 mybatis를 연동하는 블로그를 작성한 바가 있다. 

mybatis를 사용함으로 인하여, 데이터베이스와 자바 객채 간의 매핑작업을 단순화하여 진행할 수 있었다. 

 

만약, 객체 안의 데이터가 일대다의 관계를 형성하고 있다면.. 어떻게 해야 될까?

mybatis에는 resultMap의 Collection으로 이를 활용할 수 있다. 

 

자세한 것은 실습을 통해서 알아보자!!

 

활용하기

가정) 교사와 그 교사하위의 학생 리스트 데이터를 제공해야 됨. 

(교사 : 학생)은 (1 : N)의 구조를 가지고 있다. 

 

DTO 객체 생성

@Getter
@AllArgsConstructor
@NoArgsConstructor
public class TeacherDto {

  private String teacherId;
  private String teacherName;
  private List<StudentDto> studentList;


  @Getter
  public static class StudentDto {

    private String studentId;
    private String studentName;
  }

}

 

Mapper.java

public interface TeacherMapper {

  TeacherDto findTeacherStudentList(String teacherId)
}

 

Mapper.xml 생성

<resultMap id="TeacherStudentMap" type=" --- TeacherDto 객체 경로">
        <id property="teacherId" column="teacher_id" />
        <result property="teacherName" column="teacher_name" />
        <collection property="studentList" ofType=" --- StudentDto객체 경로" javaType="List">
            <id property="studentId" column="student_id" />
            <result property="studentName" column="student_ame" />
        </collection>
</resultMap>


<select id="findTeacherStudentList" resultMap="TeacherStudentMap">
    select
	th.teacher_id,
	th.teacher_name,
	st.student_id,
	st.student_name
    from teacher th, student st --교사, 학생테이블
    th.teacher_id = st.teacher_id
    th.teacher_id = #{teacherId}
</select>
<collection 상세 속성>
column 테이블간의 참조가 되는 컬럼 지정 (ex. teacher_id)
ofType  매핑되는 자바의 객체 패키지 경로 지정(ex. Student객체 경로)
javaType 해당 필드 전체의 타입을 지정 (ex. List)
property java 객체에 담는 필드 (tearcherId)

 

끝으로

1. DTO.java 객체 생성

2. Mapper.java 작성 

3. mapper.xml에 쿼리 작성 → resultMap, collection을 통하여 DTO객체에 맞게 커스텀.