7.1 Statement Generation Rules
SQL enhancement rules simplify dynamic SQL development. Compared with XML tags, rules handle empty parameters, connectors (AND/OR), and comma separators more intelligently.
| Rule | Description |
|---|---|
@{and} / @{ifand} | Smartly append AND conditions. |
@{or} / @{ifor} | Smartly append OR conditions. |
@{in} / @{ifin} | Expand collection parameters to IN (v1, v2). |
@{set} / @{ifset} | Smartly handle commas in SET clause of UPDATE statements. |
@{if} / @{iftext} | General condition check (Parse / Direct). |
@{text} | Output text fragment as-is (no argument parsing). |
@{case} / @{when} / @{else} | Multi-branch logic (Switch / If-Else). |
@{macro} / @{ifmacro} | Include predefined SQL macro fragments. |
@{md5} | Calculate parameter MD5 value. |
@{uuid32} / @{uuid36} | Generate UUID. |
@{pairs} | Iterate over Map/List to generate parameter templates. |
AND, IFAND Rules
Solves the problem of dynamically concatenating AND conditions in WHERE clauses.
@{and, sql fragment}: Automatically appends the SQL fragment when arguments in the fragment are non-null (or it contains${...}injection).@{ifand, OGNL condition, sql fragment}: Appends the SQL fragment when the OGNL condition expression is true (arguments are retained even if null).
Difference between and and ifand
| Feature | @{and, sql fragment} | @{ifand, OGNL condition, sql fragment} |
|---|---|---|
| Activation | Takes effect when at least one argument in the SQL fragment are non-null | Takes effect when the OGNL condition expression is true |
| Null arguments | When all arguments are null or there are no arguments, the entire fragment is discarded | When the condition is met, null arguments are retained |
| Typical use | Concise syntax with automatic null checking | Custom judgment logic needed |
Features
- Context-aware connectors: The rule inspects the preceding
WHERE,AND, orORto decide whether to add a connector. Write the predicate directly, for exampleWHERE @{and, x=:x}; do not add a leading AND inside the rule. - Smart Null Discard:
- By default, if
:valin@{and, col=:val}is empty (null), the entire fragment is discarded. - Exception: If the fragment contains
${...}dynamic injection, it is forced to be retained even if the parameter is empty (preventing accidental deletion of filter logic).
- By default, if
Examples
- Using Rules
- XML Comparison
Example: status is required, userId is optional. No need to manually handle WHERE/AND connectors.
select * from users
where status = :status -- Fixed condition
@{and, uid = :userId} -- Automatically handles AND prefix
-- To apply an explicit condition, replace the preceding rule with:
-- @{ifand, userId != null && userId.length() > 0, uid = :userId}
select * from users
where status = ? and uid = ?
<select id="queryUser">
select * from users
where status = #{status}
<if test="userId != null">
and uid = #{userId}
</if>
</select>
- Auto WHERE Completion: If the rule is at the beginning of the condition, it automatically adds the
WHEREkeyword. - Context-aware Connectors: Checks preceding SQL to decide whether to add
AND; it does not strip a handwritten leadingANDfrom the rule body. - Preserve Existing Connectors: If preceding SQL ends with
OR, no extraANDis added.
OR, IFOR Rules
Solves the problem of dynamically concatenating OR conditions in WHERE clauses. Symmetric with the AND rule.
@{or, sql fragment}: Automatically appends the SQL fragment when arguments are non-null.@{ifor, OGNL condition, sql fragment}: Appends the SQL fragment when the OGNL condition is true (arguments are retained even if null).
- Using Rules
- XML Comparison
Example: Match username or email. Automatically handles OR connectors.
select * from users
where username = :username
@{or, email = :email} -- Automatically connects with OR
-- To apply an explicit condition, replace the preceding rule with:
-- @{ifor, email != null && email.contains("@"), email = :email}
select * from users
where username = ? or email = ?
<select id="queryUser">
select * from users
where username = #{username}
<if test="email != null">
or email = #{email}
</if>
</select>
Like the AND rule, it adds WHERE or OR according to preceding SQL. Write the condition directly inside the rule, without a leading connector.
IN, IFIN Rules
Used to simplify concatenating IN clauses by automatically flattening collection parameters. Supports List, arrays (including primitive type arrays such as int[]).
@{in, :param}: Automatically flattens collection/array parameters into(?, ?, ...).@{ifin, OGNL condition, :param}: Effective only when the OGNL condition is true.
- Using Rules
- XML Comparison
Example: Query users whose ID is in a list.
select * from users
where status = :status
@{in, and id in :ids} -- Automatically expands to id in (?,?,?)
-- To apply an explicit condition, replace the preceding rule with:
-- @{ifin, ids != null && ids.size() > 0, and id in :ids}
select * from users
where status = ? and id in (?, ?, ?)
<select id="queryUser">
select * from users
where status = #{status}
<if test="ids != null and ids.size() > 0">
and id in
<foreach collection="ids" item="id" open="(" separator="," close=")">
#{id}
</foreach>
</if>
</select>
This rule does not automatically complete AND/OR prefixes; you need to write them manually within the rule (as and id in ... in the example). An empty or null collection emits no content. If an empty collection should match no rows, return an empty result before querying or explicitly append 1=0; do not let an omitted condition broaden a query or modification.
SET, IFSET Rules
Dedicated to UPDATE statements to solve the problem of comma concatenation during dynamic column updates.
@{set, sql fragment}: Appends an assignment and automatically manages commas. Unlikeand/or,setallows argument values to be null.@{ifset, OGNL condition, sql fragment}: Effective only when the OGNL condition is true.
- Using Rules
- XML Comparison
Example: Update a user; a null status is also written as NULL.
update users
set update_time = now() -- Fixed column
@{set, status = :status} -- Automatically handles comma
-- To update conditionally, replace the preceding rule with:
-- @{ifset, status != null && status != 'disabled', status = :status}
where uid = :uid
update users
set update_time = now(), status = ?
where uid = ?
<update id="updateUser">
update users
set update_time = now()
, status = #{status}
where uid = #{uid}
</update>
Tips
When mixing manual SQL (e.g., fixed_col = 1) between @{set} rules, no manual comma is needed.
The rule engine automatically detects preceding content and intelligently supplements commas. Manually adding commas may lead to syntax errors in some dynamic scenarios.
update users set
fixed_col = 1 -- No comma at the end
@{set, name = :name} -- Rule automatically handles preceding comma (generates ", name = ?")
@{set, age = :age}
where id = :id
UPDATE tb_user SET
@{set, name = :name}, -- ❌ Rule cannot remove the trailing comma
fixed_col = 123,
@{set, email = :email} -- ❌ Rule won't add a new comma but also won't remove the one from the previous condition
WHERE id = :id
IF, IFTEXT Rules
General conditional judgment rules. When the test expression is true, include content in the final SQL.
Although similar functionality, they handle content very differently:
@{if, test, content}: Smart Parsing. Fully parsescontent, supporting nested dynamic rules (like@{in}) and parameter placeholders. This is the most common way.@{iftext, test, content}: Native Raw Output. Performs NO parsing oncontent, appending it directly to SQL as-is. Used for injecting special keywords or syntax fragments that do not support parameterization.
- Using Rules
- XML Comparison
select * from users where 1=1
-- 1. Standard @{if}: Supports parsing internal @{in} and parameter :name
@{if, hasName, and name = :name}
@{if, idList != null, and id in @{in, :idList}}
-- 2. Raw @{iftext}: Injects SQL fragment as-is (no parameter parsing)
@{iftext, status > 2, and age = 36 }
select * from users where 1=1
and name = ? -- @{if} parses parameters normally
and id in (?, ?) -- @{if} allows nested @{in}
and age = 36 -- @{iftext} performs raw concatenation
<select id="queryUser">
select * from users where 1=1
<!-- @{if} corresponds to standard <if> -->
<if test="hasName">
and name = #{name}
</if>
<if test="idList != null">
and id in ...
</if>
<!-- @{iftext} corresponds to pure text concatenation -->
<if test="status > 2">
and age = 36
</if>
</select>
TEXT Rule
Outputs a text fragment as-is, without parsing argument placeholders or nested rules.
@{text, content}: Appendscontentdirectly to the SQL as-is.
select * from users where 1=1
@{text, and status = 'active'}
select * from users where 1=1
and status = 'active'
@{text, content}outputs unconditionally, equivalent to@{iftext, , content}.@{iftext, test, content}only outputs when thetestcondition is true.
CASE, WHEN, ELSE Rules
Provides branch logic during SQL generation stage, supporting both Switch (value matching) and If-Else (condition matching) modes.
- Switch Mode
- If-Else Mode
- XML Comparison
Value Match: @{case} first parameter is a variable.
select * from users where @{case, userType,
@{when, 'admin', role = 'administrator'},
@{when, 'manager', role = 'manager'},
@{else, role = 'visitor'}
}
select * from users
where role = 'administrator'
Expression Match: @{case} first parameter is empty.
select * from users where @{case, ,
@{when, userType == 'admin', role = 'administrator'},
@{when, userType == 'manager', role = 'manager'},
@{else, role = 'visitor'}
}
select * from users
where role = 'administrator'
<select id="queryUser">
select * from users where
<choose>
<when test="userType == 'admin'">role = 'administrator'</when>
<when test="userType == 'manager'">role = 'manager'</when>
<otherwise>role = 'visitor'</otherwise>
</choose>
</select>
- Mode Switching: Switch between Switch / If-Else modes based on whether the first parameter of
@{case}is present. - Switch Value Matching: The
valin@{when, val}is evaluated via OGNL, then compared with the evaluated result of@{case, expr}usingequals(). Mismatched types (e.g.,Integer(1)vs"1") will fall back toString.valueOf()comparison. - Else:
@{else}must be written at the end. - Default: If no match and no
else, outputs an empty string.