MyBatis | Dynamic SQL | bind

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">
    <bind name="parameter" value="'@@@' + _parameter + '@@@'"/>
    select *
      from test_table
     where value = #{parameter}
  </select>
</mapper>

Main.java

package sample.mybatis;

import java.io.InputStream;

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", "abc");
            }
        }
    }
}

Execution result

[DEBUG] s.m.selectTest  - ==>  Preparing: select * from test_table where value = ? 
[DEBUG] s.m.selectTest  - ==> Parameters: @@@abc@@@(String)

Explanation

  • You can define a temporary variable with the <bind> tag.
  • Define the temporary variable name in the name attribute.
  • In the value attribute, define a value using an OGNL (Object Graph Navigation Language) expression.
  • _parameter is an implicit variable that references the value passed as a parameter. See special parameter names.