MyBatis Dynamic SQL Tutorial: Using if, choose, trim, foreach, and bind Tags
This tutorial demonstrates how to leverage MyBatis dynamic SQL features—including if, choose, trim, foreach, and bind tags—to build flexible SELECT, INSERT, UPDATE, and DELETE statements with conditional logic, code examples, and test cases for Java backend development.
MyBatis provides powerful dynamic SQL capabilities that simplify conditional query construction compared to raw JDBC.
1. Data Preparation
A Maven project mybatis-dynamic is created with a student table containing fields such as student_id, name, phone, email, sex, and timestamps.
2. Conditional Tags
if tags are used to add WHERE clauses only when parameters are non‑null. Example:
SELECT * FROM student WHERE 1=1
<if test="name != null and name != ''">AND name LIKE concat('%', #{name}, '%')</if>
<if test="sex != null">AND sex = #{sex}</if>The same pattern applies to UPDATE statements, inserting only non‑null columns.
3. choose/when/otherwise
The choose construct mimics if‑else logic. Example for selecting by ID or name:
SELECT * FROM student WHERE 1=1
<choose>
<when test="studentId != null">AND student_id = #{studentId}</when>
<when test="name != null and name != ''">AND name = #{name}</when>
<otherwise>AND 1=2</otherwise>
</choose>4. trim and set
The where and set tags can be replaced by trim to automatically remove leading AND / OR and add appropriate prefixes or suffixes.
5. foreach
foreachiterates over collections for IN clauses or batch inserts. Example for selecting by a list of IDs:
SELECT * FROM student WHERE student_id IN
(<foreach collection="list" item="id" separator="," >#{id}</foreach>)For batch insertion:
INSERT INTO student (name, phone, email, sex, locked) VALUES
<foreach collection="list" item="student" separator=",">
(#{student.name}, #{student.phone}, #{student.email}, #{student.sex}, #{student.locked})
</foreach>6. bind
The bind tag creates a temporary variable, useful for database‑specific syntax differences, e.g., creating a nameLike parameter for Oracle and MySQL.
7. Testing
JUnit test methods illustrate each dynamic SQL scenario, printing generated SQL and result sets to verify correct behavior.
All code examples are available at https://github.com/homejim/mybatis-examples .
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java Architect Essentials
Committed to sharing quality articles and tutorials to help Java programmers progress from junior to mid-level to senior architect. We curate high-quality learning resources, interview questions, videos, and projects from across the internet to help you systematically improve your Java architecture skills. Follow and reply '1024' to get Java programming resources. Learn together, grow together.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
