https://skroy0513.tistory.com/70
위 포스팅에 이어서 오늘은 MyBatis의 동적쿼리를 알아보도록 하자.
동적 쿼리란, 런타임 중에 조건에 따라 쿼리를 생성하고 실행하며 상황에 따라 다른 문법의 SQL을 적용하는 것을 말한다.
동적 쿼리를 사용하면 사용자의 입력이나 프로그램의 상황에 따라 쿼리가 동적으로 변할 수 있다.
<if>
test 속성값이 true로 판정되면 태그 내의 SQL 구문이 사용된다.
<select id="getBooks" resultType="vo.Book">
select *
from books
where book_title = #{title}
<if test="status != 'active'">
and book_deleted = 'N'
</if>
</select>
// 제시된 검색 조건을 동시 선택이 가능한 경우는 각각의 경우마다
// if태그를 사용해서 조건별로 사용할 SQL 구문을 지정해야 한다.
<select id="serchComputer" parameterType="map" resultType="vo.Book">
select *
from computers
where product_deleted = 'N'
<if test="company != null">
and product_company = #{company}
</if>
<if test="cpu != null">
and cpu_type = #{cpu}
</if>
<if test="os != null">
and os_type = #{os}
</if>
</select
<choose> ~ <when> ~ <otherwise>
검색 조건이 여러 개인 경우 사용하며, 해당 검색 조건은 그중에 하나만 사용할 수 있는 경우에 사용된다.
// 책을 검색할 때 제목, 저자, 내용 중에 하나만 검색조건이 된다.
<select id="searchBooks" parameterType="map" resultType="vo.Book">
select *
from books
where book_deleted = 'N'
<if test="cat != null">
and book_category = #{cat}
</if>
<choose>
<when test="opt == 'title'">
and book_title = #{keyword}
</when>
<when test="opt == 'writer'">
and book_writer = #{keyword}
</when>
<when test="opt == 'writer'">
and book_content like '%' || #{keyword} || %
</when>
</choose>
</select>
<foreach>
컬렉션타입의 파라미터값을 반복처리한다. 주로 in 연산자와 함께 사용된다.
주요 속성
- collection : 반복처리할 컬렉션이 저장되는 변수명
- item : 반복이 수행되는 동안 컬렉션에서 하나씩 꺼낸 값이 저장되는 변수
- index : 반복이 수행되는 동안 컬렉션에서 하나씩 꺼낸 값의 인덱스가 저장되는 변수
- open : foreach 태그로 반복처리를 하기 전에 표시할 SQL 구문을 지정한다.
- close : foreach 태그로 반복처리가 종료되었을 때 표시할 SQL 구문을 지정한다.
- separator : foreach 태그로 반복처리되는 값을 구분하는 구분자를 지정한다.
<select id="searchComputers" parameterType="map" resultType="vo.Computer">
select *
from computers
where computer_on_sell = 'Y'
<foreach item="cpuType" index="index" collection="cpuTypes"
open="and cpu_type in (" separator="," close=")">
#{cpuType}
</foreach> // and cpu_type in ('i3', 'i5')
</select>
<where>
사용가능한 SQL이 있는 경우에 where 키워드를 추가하고, 사용가능한 SQL 구문이 and나 or로 시작한다면 and나 or를 지운다.
모든 조회조건이 동적 SQL로 구성되는 경우에 사용한다. (where절이 고정으로 있는 경우에는 사용하지 않음)
<select id="searchEmployees" parameterType="map" resultType="vo.Employee">
select *
from employee
<where>
<if test="job != null">
job_id = #{job}
</if>
<if test="dept != null">
and department_id = #{dept}
</if>
<if test="manager != null">
and manager_id = #{manager}
</if>
</where>
</select>
오류상황
// 1번째 상황 -> 오류 없음
Map<String, Object> param = new HashMap<>();
param.put("job", "IT_PROG");
employeeMapper.searchEmployees(param);
select *
from employee
where
job_id = 'IT_PROG'
// 2번째 상황 -> and 연산자 때문에 오류
Map<String, Object> param = new HashMap<>();
param.put("dept", 60);
employeeMapper.searchEmployees(param);
select *
from employee
where
and department_id = 60
// 3번째 상황 -> where 뒤에 아무것도 없어서 오류
Map<String, Object> param = new HashMap<>();
employeeMapper.searchEmployees(param);
select *
from employee
where
<set>
update 호출 시 파라미터가 있는 칼럼만 SET절을 만들도록 한다.
<update id="update" parameterType="map">
update book
<set>
<if test="title != null">book_title=#{title},</if>
<if test="writer != null">book_writer=#{writer},</if>
<if test="content != null">book_content=#{content},</if>
</set>
where on_sell = 'Y'
</update>
// 만약 파라미터에 title과 contenr만 null이 아니라면
// update book
// set book_title = #{title},
// book_content = #{content)
// where on_sell = 'Y'
// 의 쿼리가 작성된다
'멋진 개발자 > Java & Spring' 카테고리의 다른 글
개발자 성장 기록 61 - JVM의 실행 엔진 (Execution Engine) (0) | 2024.05.10 |
---|---|
개발자 성장 기록 60 - Bean (0) | 2024.05.09 |
개발자 성장 기록 54 - JSP (0) | 2024.04.23 |
개발자 성장 기록 53 - Java의 동일성, 동등성 (0) | 2024.04.22 |
개발자 성장 기록 51 - MyBatis (0) | 2024.04.18 |