IT 일기장

[MyBatis] association tag 활용 본문

프로그래밍 언어/XML

[MyBatis] association tag 활용

뽕슈 2021. 12. 7. 11:13
반응형

사이트별로 메뉴를 분기시키기 위해 이리저리 찾아보다 쿼리가 반복을 돌고 있었는데 여기서 잠깐 막혔었다.

"java, mybatis에서 반복문을 쓰지도 않았는데 어떻게 쿼리가 반복해서 돌지?"

찾다가 발견한 코드가 있었는데 음.. 딱 봤을때 이게 뭔가 싶었다.

<resultMap id="recursiveMenu" extends="menu" type="egovframework.itgcms.core.main.service.MngrManagerMenuVO">
	<id property="id" column="c_code" /><!-- 필수 설정 primary key -->
	<result property="minDepth" column="minDepth" />
	<result property="maxDepth" column="maxDepth" />
	<result property="schStr" column="schStr" />
	<result property="schLicenseType" column="schLicenseType" />
	<result property="act" column="act" />
	<association property="mngrManagerMenuList" column="{id=c_code,minDepth=minDepth,maxDepth=maxDepth,schStr=schStr,schLicenseType=schLicenseType,act=act}" select="mngrManagerMenuListRecursive" />
</resultMap>

assciation tag에 select 속성을 찾아가봤더니 SELECT 쿼리문을 적은 곳을 찾게 되더라!

그래서 이걸보고 아.. column에다가 추가해서 사용할 수 있구나 생각하고 추가해서 사용했다.

    <select id="mngrManagerMenuListRecursive" resultMap="recursiveMenu">
    /***** mngrManagerMenuListRecursive *****/
    select
		a.c_code,
		a.c_name,
		a.etc1,
		a.etc2,
		a.c_depth,
		a.c_pcode,
		a.c_order,
		<!-- 컬럼추가 -->
		#{minDepth} minDepth,
		#{maxDepth} maxDepth,
		#{schStr} schStr,
		#{schLicenseType} schLicenseType,
		#{act} act,
		(select count(*) from t_code b where b.c_pcode = a.c_code and b.delyn = 'N') subtree
		from t_code a
		where a.delyn = 'N'
			<if test="id != null and id != ''">
				and c_pcode = #{id}
			</if>
			<if test='schLicenseType != "M"'>
				and c_code not in ('SITE')
			</if>
			and a.c_auth &lt;= #{schStr}
			and a.c_depth &gt;= #{minDepth}
		order by a.c_depth, a.c_order
    </select>

이해하고 써먹은건 좋은데 association tag.. 이게 뭔가 싶었다.

구글링해서 좀 찾아봤는데 이해하기 쉽던 예시가 있었다. 내용은 즉슨

Artist - Album - Songs

한명의 가수에게는 N개의 앨범이 있고 또 1개의 앨범에는 N개의 노래들이 있다.

그럼 다음과 같은 질문이 있을때 어떻게 처리를 하냐는거다.

가수 OOO 3집 앨범의 코드 트랙 35번 노래를 찾으려면 어떻게 해야될까?

3집 앨범 정보 넣고 코드 트랙 값을 다 아는 상황에서 짜면 1번만 돌리면 되지 그런데 모르는 상황이라면..

 

1. 가수를 쿼리문 돌려서 찾는다

2. OOO 가수의 3집 앨범을 쿼리문 돌려서 찾는다

3. 3집 앨범 뭐있는지 반복문 돌려서 35번 노래 찾는다.

 

노래 한번 찾는다고 DB를 3번이나 돌리니까 비효율적이다. 이처럼 1:N 관계에서 유용하게 쓰일 수 있는 코드를 발견해서 나름 기분이 좋다

반응형
Comments