ORM & SQL Mapper
Association & Collection
wavid
2020. 11. 26. 03:12
MyBatis는 쿼리를 이용해 데이터를 조회 시 매핑되는 객체가 또 다른 객체를 의존하는 형태로 갖고 있는 경우 그 의존하는 객체의 값도 한꺼번에 조회하는 기능을 제공함. (JPA로 치면 fetch join같은 기능?)
Association (has one, 일대일 관계)
Association은 has one 타입의 관계를 다룰 때 적용 가능함.
예시로 어떤 시험지(Sheet)를 푸는 학생(Stuent)은 한 명인 경우를 객체로 표현하면 아래와 같다.
class Sheet {
...
Student student;
}
class Student {
int studentId;
...
}
위와 같이 시험지와 학생이 일대일 관계를 갖는 경우에 MyBatis의 Association을 이용해서 Sheet 조회 시 Student도 같이 조회해서 매핑하도록 처리할 수 있음.
<resultMap id="sheetResult" type="com.xxx.Sheet">
<association property="student" column="studentId" javaType="Student" select="selectStudent"/>
</resultMap>
<select id="selectSheet" resultMap="sheetResult">
SELECT * FROM sheet WHERE sheet_id = #{sheetId}
</select>
<select id="selectStudent" resultType="Student">
SELECT * FROM student WHERE student_id = #{studentId}
</select>
Collection (has many, 일대다 관계)
Collection은 has many 타입의 관계를 다룰 때 적용 가능함.
한 시험지(Sheet)에 여러 문항(Pool)이 존재하는 경우를 객체로 표현하면 아래와 같다.
class Sheet {
...
List<Pool> pools;
...
}
class Pool {
...
int sheetId;
...
}
이 경우에는 Collection을 이용하면 된다.
selectSheet를 호출하게 되면 selectSheet 처리하면서 그 sheetId에 해당하는 모든 pool 정보가 조회되서 매핑될 것이다.
<resultMap id="sheetResult" type="Sheet">
<collection property="pools" javaType="ArrayList" column="sheetId" ofType="Pool" select="selectPools"/>
</resultMap>
<select id="selectSheet" resultMap="sheetResult">
SELECT * FROM sheet WHERE sheet_id = #{sheetId}
</select>
<select id="selectPools" resultType="Pool">
SELECT * FROM pool WHERE sheet_id = #{sheetId}
</select>
[참고 및 출처]
noveloper.github.io/blog/spring/2015/05/31/mybatis-assocation-collection.html