MyBatis | Dynamic SQL | choose, when, otherwise

DB table

test_table

id value
1 hoge
2
3 piyo

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
    <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);
            }
        }
    }
}

Execution result

[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]

Explanation

  • Use the <choose> tag to define a condition that applies one option from multiple choices.
  • The SQL in a <when> tag is written when the specified condition is satisfied.
  • The SQL in an <otherwise> tag is written when none of the other conditions are satisfied.