반응형

작성일자 : 2021.02.12

시나리오 : MyBatis 를 사용하여 DB 데이터를 조회할 때 1:M 관계를 가지는 데이터를 List 형태로 조회

환경 : Spring Boot, mybatis-spring-boot-starter 1.3.2

 

 

1. 조회 데이터 정의

 

Parent(1) : Child(M) 구조의 테이블 정의

 

1개의 Parent 데이터와, Parent 와 식별관계를 가지는 2개의 Child 데이터를 저장. Child 는 Parent 의 id 를 FK 로 가짐

 

 

2. 설정

 

* resultMap 을 활용

In Mapper.xml

<resultMap id="parentResultType" type="com.example.demo.Parent">
    <id column="PK 칼럼명" property="멤버 변수명"/>
    <result column="칼럼명" property="멤버 변수명"/>
    <collection property="childList" resultMap="childList"/>
</resultMap>

<resultMap id="childList" type="com.example.demo.Child>
    <id column="PK 칼럼명" property="멤버 변수명"/>
    <result column="칼럼명" property="멤버 변수명"/>
    <result column="칼럼명" property="멤버 변수명"/>
</resultMap>

<select id="selectId" resultMap="parentResultType">
   ...
</select>

 

Mapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.example.demo.TestMapper">
  
  <resultMap id="parentResultType" type="com.example.demo.Parent">
    <id column="parentId" property="id"/>
    <result column="parentValue" property="value"/>
    <collection property="childList" resultMap="childList"/>
  </resultMap>
  
  <resultMap id="childList" type="com.example.demo.Child">
    <id column="childId" property="id"/>
    <result column="parentId" property="parentId"/>
    <result column="childValue" property="value"/>
  </resultMap>

  <select id="selectParentList" resultMap="parentResultType">
    SELECT
      t1.id AS parentId
      , t1.value AS parentValue
      , t2.id AS childId
      , t2.value AS childValue
    FROM
      parent t1
    LEFT JOIN child t2
    ON t1.id = t2.parentId
  </select>
  
</mapper>

 

Parent.java

public class Parent {
    String id;
    String value;
    List<Child> childList = new ArrayList<>();
}

 

Child.java

public class Child {
    Integer id;
    Integer parentId;
    String value;
}

 

 

3. 확인

 

Mapper 에서 정의한 selectParentList 쿼리를 사용하여 1. 의 환경의 DB 에서 조회할 경우,

 

- 실제 쿼리 조회 내용

 

- 조회한 데이터 내용

 

중복이 제거되고 childList 형태의 멤버 변수가 조회됌 

반응형

'Java' 카테고리의 다른 글

[Spring] Profile 기준 Property 구분 적용  (0) 2023.06.28
[SpringBoot] Gradle 변수 Property 활용  (0) 2022.05.30
[Spring] Web Cache 적용  (0) 2020.12.19
[SpringBoot] H2 연동  (0) 2020.07.21
[Spring] App 구동 후 자동 작업 실행  (0) 2020.02.23

+ Recent posts