본문 바로가기

it-day

Mapper xml 에서 sql , include

<sql> 태그와 <include> 태그

MyBatis는 <sql> 태그와 <include> 태그를 이용해서 공통으로 사용되거나 반복적으로 사용되는 쿼리를 처리할 수 있습니다. 굳이 Java로 비유하자면, 변수로 선언해 두고 필요한 상황에 호출해서 사용하는 개념과 유사한데요. 저는 PostMapper.xml의 "postColumns"와 같이 INSERT 쿼리와 SELECT 쿼리에 주로 사용합니다.


각각의 쿼리에 전체 칼럼을 선언해 줘도 되지만, 해당 태그들을 이용하면 코드 라인을 줄일 수 있습니다. 
두 태그의 포인트는 중복 제거이며, 동일한 XML Mapper뿐만 아니라, 다른 XML Mapper에 선언된 SQL 조각도 인클루드(Include) 할 수 있습니다.

 

출처 : 도뎡 블로그

 

<select id="getPage" resultType="int">

     select pageNum from vam_board where bno = #{bno}

</select>

<select id="getTitle" resultType="String">

     select title from vam_board where bno = #{bno}

</select>

<select id="getContent" resultType="String">

    select content from vam_board where bno = #{bno}

</select>

 

3개의 쿼리를 보면 공통적으로 똑같은 where절이 중복되어서 사용되고 있습니다.

이러한 경우에 <sql>과 <include> 태그를 중복된 코드를  줄여줄 수 있습니다.

 

<sql id="where">

    where bno = #{bno}

</sql>

 

<select id="getPage" resultType="int">

    select pageNum from vam_board <include refid="where"></include>

</select>

 

<select id="getTitle" resultType="String">

     select title from vam_board <include refid="where"></include>

</select>

 

<select id="getContent" resultType="String">

    select content from vam_board <include refid="where"></include>

</select>

 

출처 : https://kimvampa.tistory.com/176

 

'it-day' 카테고리의 다른 글

AJax  (0) 2023.10.19
java list에서 원하는 값 가져오기  (0) 2023.10.18
Mysql 형변환(varchar -> int)  (0) 2023.10.17
daterangepicker 상세 사용법  (0) 2023.10.06
Thymeleaf 반복 상태 변수 (status)  (0) 2023.10.06