MyBatis | 동적 SQL | if
DB 테이블
test_table
| id | string_value | number_value | 
|---|---|---|
| 1 | hoge | 100 | 
| 2 | hoge | 200 | 
| 3 | fuga | 300 | 
| 4 | piyo | 400 | 
소스 코드
sample_mapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="sample.mybatis">
  <select id="selectTest" resultType="sample.mybatis.TestTable">
    select *
      from test_table
     where string_value = 'hoge'
     <if test="numberValue != null"> <!-- if 태그에서 조건 분기 -->
       and number_value = #{numberValue}
     </if>
  </select>
</mapper>
Main.java
package sample.mybatis;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class Main {
    public static void main(String[] args) throws Exception {
        try (InputStream in = Main.class.getResourceAsStream("/mybatis-config.xml")) {
            SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
            try (SqlSession session = factory.openSession()) {
                session
                    .selectList("sample.mybatis.selectTest") // 매개 변수 미설정
                    .forEach(System.out::println);
                Map<String, Object> param = new HashMap<>();
                param.put("numberValue", 100);
                session
                    .selectList("sample.mybatis.selectTest", param) // 매개 변수 설정
                    .forEach(System.out::println);
            }
        }
    }
}
실행 결과
[DEBUG] s.m.selectTest  - ==>  Preparing: select * from test_table where string_value = 'hoge' 
[DEBUG] s.m.selectTest  - ==> Parameters: 
[DEBUG] s.m.selectTest  - <==      Total: 2
TestTable [id=1, stringValue=hoge, numberValue=100]
TestTable [id=2, stringValue=hoge, numberValue=200]
[DEBUG] s.m.selectTest  - ==>  Preparing: select * from test_table where string_value = 'hoge' and number_value = ? 
[DEBUG] s.m.selectTest  - ==> Parameters: 100(Integer)
[DEBUG] s.m.selectTest  - <==      Total: 1
TestTable [id=1, stringValue=hoge, numberValue=100]
설명
- <if>태그를 사용하여 조건이 충족된 경우에만 SQL을 추가 시키거나 삭제할 수 있게 된다.
- test 속성에서 조건식을 기술한다.
- 이 가운데는 검색 조건에 전달할 매개 변수의 값을 참조할 수 있다.
- AND나 OR 조건을 작성할 때, and, or를 사용한다(&&,||가 아니다!).