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を使用する(&&||ではない)。