View

MyBatis : sql, include 태그란?

curioser 2019. 12. 28. 16:01

 MyBatis를 통해 데이터베이스를 가져오는 과정에서

mapper 클래스 내에 쿼리문이 중복되는 경우가 상당 수 생긴다.

 

나 같은 경우는 특히나 select할 때 그런 일이 자주 발생했다. 

이럴때 sql태그를 사용하면 훨씬 깔끔하고 수월하게 쿼리문을 실행할 수 있다.

 


1) sql문 안에 중복되어 사용되는 값들을 넣어줌

2) 값들을 사용할 때는 include문을 써서 사용하면 된다. 

1
2
3
4
5
6
7
8
9
10
11
12
<mapper>  
    <sql id="test">
        id, pwd, name
    </sql>
    
    <select id="testMemberList" resultType="member">
        select 
        <include refid="test" />
        from member
    </select>
</mapper>
 
cs

 

위의 쿼리문은 아래의 쿼리문을 실행한것과 같다.

1
2
3
4
5
6
7
<mapper>  
    <select id="testMemberList" resultType="member">
        select id, pwd, name
        from member
    </select>
</mapper>
 
cs

 


 중복되는 값 뿐만 아니라 if문을 써서 해당하는 값을 가져오기에도 수월하다

먼저 회원리스트 중 아이디와 이름을 검색해서 값을 가져오기로 한다고 가정

sType 은 아이디인지 이름인지 구별해서 찾는 것,

key는 검색창에 검색하고자 하는 값을 넣은 것이다.

 

1) sql문안에 만약 'i'면 아이디로 검색하고 , 'n'이면 이름으로 검색하는 if태그를 작성한다

2) select문에서 이에 해당하는 값이 검색되도록 include 태그를 삽입해준다 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<mapper>
    <sql id="s">
        <if test="sType == 'i'.toString()">
           and mem_id like '%'||#{key}||'%'
        </if>
        <if test="sType == 'n'.toString()">
           and mem_name like '%'||#{key}||'%'
        </if>
    </sql>
 
    <select id="searchMem" resultType="mem">
        select *
       from mem
        where id is not null
        <include refid="s" />
       order by rgd desc
    </select>
</mapper>
cs

 sql 문을 적용하면 이렇게 아이디로 검색이 가능해진다.

'dataBase' 카테고리의 다른 글

Oracle :: 다중 INSERT 하기  (0) 2021.06.16
SQL : DML(Data Manipulation Language) - INSERT, DELETE, UPDATE  (1) 2019.12.30
Share Link
reply
«   2024/10   »
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