[spring]동적쿼리

·2024년 6월 3일
0

spring

목록 보기
6/8
post-thumbnail

동적 쿼리

특정 상황에 따라 SQL 을 동적으로 만드는 것을 말한다

🍎<if test=" ">
  	test 속성을 만족하면 태그 안 내용을 쿼리에 추가하겠음 .
  
  
🍎<choose>-<when>-<otherwise> 
  if-elseif-else 라고 생각하면 이해하기 쉽다 !
 
  
🍎<where>
  	조건절을 만들 때 사용한다
  	하위 요소에서 내용이 생성되는 경우에만 ! where 이 생긴다
  
🍎<set>
  	update문장에서 null 여부에 따라 동적으로 쿼리를 만든다

직접 사용해보자

ProductMapper.xml


<mapper namespace="com. ~~ (경로)"

<!-- 이건 그냥 insert -->
<insert id="insert">
	insert into product
    values (seq_product.nextval, #{name},#{price},#{category}, #{description})
</insert>


<!-- 동적 sql 여기 -->
<select id="findByName" resultType="ProductVO">
	select * from PRODUCT
    <if test="name != null">
    	where name like '%' || #{name} || '%'
     </if>
     
</select>


<!-- where-->
<select id="findByConditions" resultType="ProductVO">
	select * from PRODUCT
    <where>
    	<if test="name != null">
        	AND name like '%' || #{name} || '%'
        </if>
        <if test ="category != null">
        	AND category = #{category}
         </if>
         <if test="price != null">
         	AND price >= #{price}
          </if>
    </where>
</select>


💦where 태그 안에 if 문들 중 하나라도 true 가 뜨는 경우 where 를 생성한다

AND 나 OR ->만약 해당 조건이 먼저 오게 되면 자동으로 지워진다.

profile
어리둥절 빙글빙글 돌아가는 코딩세상~

0개의 댓글