티스토리 뷰
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
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- blocking
- a
- Handler Interceptor
- non-blocking
- 프로그래머스 Level 2
- 논블로킹
- 프로그래머스
- 스택/큐
- 블로킹
- 필터
- 프로그래머스 Level 1
- 인터셉터
- 비동기
- http://www.nextree.co.kr/p6960/
- 코딩테스트 고득점 Kit
- 프로그래머스 Level 3
- 핸들러 인터셉터
- Asynchronous
- Filter
- Synchronous
- 동기
- 해시
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
글 보관함