MyBatis | 動的SQL | choose, when, otherwise
DBテーブル
test_table
| id | value |
|---|---|
| 1 | hoge |
| 2 | |
| 3 | piyo |
ソースコード
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
<choose>
<when test="value == null">
where value is null
</when>
<otherwise>
where value = #{value}
</otherwise>
</choose>
</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()) {
TestTable testTable = session.selectOne("sample.mybatis.selectTest");
System.out.println(testTable);
Map<String, Object> param = new HashMap<>();
param.put("value", "hoge");
testTable = session.selectOne("sample.mybatis.selectTest", param);
System.out.println(testTable);
}
}
}
}
実行結果
[DEBUG] s.m.selectTest - ==> Preparing: select * from test_table where value is null
[DEBUG] s.m.selectTest - ==> Parameters:
[DEBUG] s.m.selectTest - <== Total: 1
TestTable [id=2, value=null]
[DEBUG] s.m.selectTest - ==> Preparing: select * from test_table where value = ?
[DEBUG] s.m.selectTest - ==> Parameters: hoge(String)
[DEBUG] s.m.selectTest - <== Total: 1
TestTable [id=1, value=hoge]
説明
<choose>タグを使用すると、複数の選択肢のうち1つを適用する条件を定義できる。<when>タグで指定した条件が満たされた場合、そのSQLを記述する。<otherwise>タグは、それ以外のすべての条件が満たされない場合にSQLを記述する。