Mybatis foreach

정재현·2022년 2월 14일

Foreach

MyBatis의 가장 강력한 기능 중 하나인 동적쿼리. 그 중 하나인 foreach에 대해 알아보자.

parametertype에 리스트를 담아 보내 줄 때 foreach문을 사용해 결과값을 가져올 수 있다.

select * from user where id in (1,2,3)

위와 같은 쿼리문을 사용할 때 범위에 해당하는 in에 (1,2,3)을 list에 담아서 전달.

foreach 속성

  • collection : 전달받은 인자 값
  • item : 전달받은 인자 값을 다른이름으로 대체할 때 사용
  • open : 해당 구문이 시작할 때 삽입되는 문자
  • close : 해당 구문이 끝 날때 삽입되는 문자
  • separator : list에서 가져올 데이터들 사이 구분할 문자
  • index : 반복되는 구문의 번호. 0부터 증가
   <select id="getFollowerFeed" parameterType="ArrayList" resultType="Board">
        select * from board where userId
        in <foreach collection="list" item="value" index="idx" separator="," open="(" close=")">
        #{value}
    </foreach> or board.view_range like "전체공개"
    </select>

=> list에 userId가 {1,2}가 있다면 아래와 같은 쿼리문이 동작

select * from board where userId in (1,2) or board.view_range like "전체공개"
profile
back end개발자로 성장하기

0개의 댓글