MyBatis | Dynamic SQL | if
DB table
test_table
| id | string_value | number_value |
|---|---|---|
| 1 | hoge | 100 |
| 2 | hoge | 200 |
| 3 | fuga | 300 |
| 4 | piyo | 400 |
Source code
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"> <!-- Branch with the if tag. -->
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") // No parameter set.
.forEach(System.out::println);
Map<String, Object> param = new HashMap<>();
param.put("numberValue", 100);
session
.selectList("sample.mybatis.selectTest", param) // Parameter set.
.forEach(System.out::println);
}
}
}
}
Execution result
[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]
Explanation
- Use the
<if>tag to add or remove SQL only when a condition is satisfied. - Write the condition expression in the test attribute.
- Inside it, you can reference parameter values passed to the search condition.
- When writing AND or OR conditions, use and and or, not
&&or||.