SoFunction
Updated on 2025-04-05

Mybatis spliced ​​dynamic sql through XML

Dynamic SQL

Dynamic SQL is a technology that constructs and executes SQL statements at runtime. Unlike static SQL, static SQL is determined at compile time, while dynamic SQL allows SQL statements to be generated based on different conditions during program execution. This flexibility makes dynamic SQL particularly suitable for scenarios where queries need to be generated based on user input or other variables.

Features of Dynamic SQL

Flexibility: SQL queries can be constructed dynamically based on user input and program logic.

Complex Query: Dynamic SQL can simplify implementation when it is necessary to decide on query conditions or tables at runtime.

Scalability: Query conditions can be added or modified easily without changing static SQL statements.

Use scenarios

Generate different queries according to user selection, such as search function.

Generate complex reports, and users can customize the fields and conditions of the reports.

In some algorithms, SQL statements need to be generated dynamically based on different conditions.

Dynamic SQL implementation method

Dynamic SQL can usually be implemented in two ways:

String stitching: Splice SQL strings in a programming language and execute.

Use dynamic execution functions provided by the database: such as using stored procedures of the database (such as the EXECUTE IMMEDIATE statement in PL/SQL) or dynamic query interfaces provided in some frameworks.

Things to note

SQL Injection: Dynamic SQL is particularly vulnerable to SQL injection attacks, so you must be careful with user input, using parameterized queries or other protection measures.

Performance: Dynamic SQL may introduce performance issues because the database may need to recompile queries every time it is executed.

Overall, Dynamic SQL provides powerful and flexible query capabilities, but requires additional attention to security and performance issues when used.

<if> tag

In MyBatis, the <if> tag is used to conditionally splice SQL statements. This is very useful in dynamic SQL, and it is possible to decide whether to include certain fields or conditions based on the provided parameters. This method can simplify SQL code and make the generated SQL more flexible.

The code example you provide shows how to use the <if> tag to decide whether to include the gender field based on the value of the gender parameter in an INSERT operation. Specifically, the following are explanations of the key parts:

Code Analysis

<insert >
    INSERT INTO userinfo (
        username,
        `password`,
        age,
        <if test="gender != null">
            gender,
        </if>
        phone)
    VALUES (
        #{username},
        #{age},
        <if test="gender != null">
            #{gender},
        </if>
        #{phone})
</insert>

Key Components

1.<if test="gender != null">:

This tag is used to check if the gender parameter is not null.

If the condition holds, that is, the gender parameter has a value, the gender field will be included in the generated SQL.

Splicing:

When gender is not null, the generated SQL will include the gender field and its corresponding value. Otherwise, this part will be skipped.

Therefore, if gender is null, the final generated SQL statement will only contain username, password, age, and phone fields without gender.

Generated SQL example

When gender is null:

INSERT INTO userinfo (username, `password`, age, phone)
VALUES (#{username}, #{password}, #{age}, #{phone})

When gender has a value:

INSERT INTO userinfo (username, `password`, age, gender, phone)
VALUES (#{username}, #{password}, #{age}, #{gender}, #{phone})

<trim> tag

In MyBatis, the <trim> tag is used for dynamic SQL generation, especially in handling the connection and modification of SQL statements. It can flexibly add or remove prefixes, suffixes, and remove unnecessary symbols based on conditions, which is very helpful for building complex SQL statements.

Basic formatting using <trim> tags

&lt;trim prefix="Prefix" suffix="suffix" prefixOverrides="The character to be overridden by the prefix" suffixOverrides="The character to be overwritten by the suffix"&gt;
    &lt;!-- The part of the conditional judgment --&gt;
&lt;/trim&gt;

Attribute description

prefix: Specifies the prefix added before the generated SQL statement. This property is often used to ensure that the generated SQL statement is logically complete. For example, if you need to generate a WHERE clause, you can set prefix to "WHERE".

suffix: Specifies the suffix added after the generated SQL statement. It is usually used to add some fixed parts at the end of a SQL statement, such as ORDER BY or LIMIT.

prefixOverrides: This property specifies prefix characters to be overwritten, and will be ignored if these characters are already included before the generated SQL statement. For example, if you set prefixOverrides="AND" and your condition starts with AND, MyBatis will automatically remove this AND.

suffixOverrides: Similar to prefixOverrides, this property is used to specify the tail character to be ignored. If the generated SQL contains these characters at the end, they will be removed. For example, if suffixOverrides="," is set and the end of the SQL has an extra comma, MyBatis will remove this comma.

Example

A typical example:

<where>
    <trim prefix="WHERE" suffixOverrides="AND">
        <if test="username != null">
            username = #{username} AND
        </if>
        <if test="age != null">
            age = #{age} AND
        </if>
    </trim>
</where>

Analysis:

In this example, <trim> is used to generate a WHERE clause.

prefix="WHERE" ensures that the generated SQL begins with WHERE.

suffixOverrides="AND" ensures that if there is an extra AND at the end of SQL, it will be removed.

Conditions are only added if username and age are not null.

summary

By using the <trim> tag and its properties, MyBatis can improve the flexibility and readability of generating SQL, avoid SQL syntax errors caused by conditional judgment, and simplify the assembled process of complex SQL statements.

<where> tag

In MyBatis, the <where> tag is used to dynamically generate WHERE clauses in SQL queries. It can dynamically construct SQL based on the existence or absence of query conditions, simplifying the operation of conditional splicing. The advantage of using the <where> tag is that it automatically handles redundant AND or OR before and after, avoiding possible SQL syntax errors when manually splicing.

Basic usage examples

Suppose we have a user table users, and we want to query based on certain attributes of the user, such as the user's name, age, and gender. We can use the <where> tag to build SQL.

<select  parameterType="map" resultType="User">
    SELECT * FROM users
    <where>
        <if test="name != null">
            AND name = #{name}
        </if>
        <if test="age != null">
            AND age = #{age}
        </if>
        <if test="gender != null">
            AND gender = #{gender}
        </if>
    </where>
</select>

illustrate

Automatic processing: When you use the <where> tag, it will automatically remove the AND or OR before the condition. For example, if name is not null, the SQL statement will generate WHERE name = #{name}; if a second condition age is added, the generated SQL will be WHERE name = #{name} AND age = #{age}.

Flexibility: You can add as many conditions as you want without worrying about extra logical connectors.

Parameter Type: In the above example, parameterType is set to map, indicating that the passed parameter is a Map object containing key-value pairs of name, age, and gender.

Things to note

The <where> tag can only be used directly at the beginning of a SQL statement and cannot be nested in other tags.

The structure generated by SQL will vary depending on the existence or absence of conditions, so it is necessary to ensure that the logical conditions can be executed correctly.

By using the <where> tag, MyBatis can help developers reduce the complexity of manually splicing SQL and improve code readability and maintainability.

<set> tag

In MyBatis, the <set> tag is usually used to dynamically generate SET clauses in UPDATE statements. Its main function is to simplify the operation of multi-condition update fields and automatically process the previous redundant commas (,) to avoid syntax errors when splicing SQL.

Basic usage examples

Suppose we have a user table, and now we need to update the user's name, age, and gender based on the user ID. The <set> tag can be used to build SQL update statements.

<update  parameterType="User">
    UPDATE users
    <set>
        <if test="name != null">
            name = #{name},
        </if>
        <if test="age != null">
            age = #{age},
        </if>
        <if test="gender != null">
            gender = #{gender}
        </if>
    </set>
    WHERE id = #{id}
</update>

illustrate

Automatically handle commas: When using the <set> tag, if the update condition of a field is satisfied, it will automatically insert commas between fields. This tag ensures that no extra commas appear after the last condition. For example, if only name and age are updated, the final generated SQL would be SET name = #{name}, age = #{age}.

Flexibility: Developers can dynamically add and delete condition fields according to specific needs without manually changing the structure of SQL statements.

Parameter Type: In the above example, parameterType is set to User, indicating that the incoming parameter is a user object with multiple attributes.

Things to note

The <set> tag is usually used in UPDATE statements and is not applicable to other types of SQL statements.

Make sure to remove the comma after the last condition (if present), which can be achieved by controlling the conditions of the <if> tag.

The <set> tag can be reused to construct content in different situations.

By using the <set> tag, MyBatis makes update operations more flexible and concise, greatly reducing the risks of developers when splicing SQL statements.

<foreach> tag

In MyBatis, the <foreach> tag is used to dynamically generate collection processing in SQL statements, especially when you need to handle a list, array, or other iterable collection. It is ideal for building IN clauses, batch inserts or update statements, etc.

Attribute description

collection: Specifies which collection of the incoming parameters will be used for traversal. This collection must be an array or Collection type.

item: Specifies the name of each element in the collection. This name is valid within the foreach tag and can be used to reference the current element.

open: Specifies the character at the beginning of the traversal, such as the opening bracket (or VALUES (. Commonly used to build SQL IN clauses.

close: Specify the character at the end of the traversal, such as the close bracket). Use with the open property.

separator: The character used to separate each element. For example, if you want to build a delimiter such as , or AND, you can use this property.

Basic usage examples

Suppose we have a user table users, and we want to query user information based on multiple user IDs, and we can use the <foreach> tag to build SQL statements:

<select  parameterType="list" resultType="User">
    SELECT * FROM users
    WHERE id IN
    <foreach collection="ids" item="id" open="(" close=")" separator=",">
        #{id}
    </foreach>
</select>

illustrate

collection="ids": Specifies that the passed in parameter is a collection named ids, which is usually a List or array containing the user ID.

item="id": In the <foreach> tag, the name of the current element is id, which is used to extract the value of each ID in the collection.

open="(" and close=")": Add brackets to the beginning and end parts of the IN clause.

separator=",": Insert commas between elements to generate SQL in the correct format.

Things to note

Parameter Type: Typically, parameterType can be set to List or other collection type.

Result Type: Use resultType to specify the returned type.

Wide applicability: In addition to the IN clause, <foreach> can also be used for batch insertion and multi-condition WHERE construction, as shown in the following example:

<insert  parameterType="list">
    INSERT INTO users (name, age, gender)
    VALUES
    <foreach collection="userList" item="user" separator=",">
        (#{}, #{}, #{})
    </foreach>
</insert>

Summarize

By using the <foreach> tag, MyBatis allows developers to flexibly process collections in SQL statements, generating variable-length SQL statements, improving the readability and dynamic construction capabilities of the code.

<include> tag

In MyBatis, the <include> tag is used for dynamic SQL construction, which makes SQL statements more reusable and maintainable. It is usually used with the <sql> tag to reuse the same SQL fragment in multiple places.

Basic usage of <include> tags

The <include> tag is used as follows:

Defining SQL snippets: First, use the <sql> tag to define a reusable SQL snippet, usually in the <mapper> tag.

Use include tag: In the main SQL statement, refer to the previously defined SQL fragment using the <include> tag.

Example

Here is a simple example showing how to use the <include> tag:

&lt;mapper namespace=""&gt;
    
    &lt;!-- Define reusable SQL Fragment --&gt;
    &lt;sql &gt;
        id, username, email
    &lt;/sql&gt;
    
    &lt;select  resultType=""&gt;
        SELECT
            &lt;include ref/&gt;
        FROM users
        WHERE id = #{id}
    &lt;/select&gt;
    
    &lt;select  resultType=""&gt;
        SELECT
            &lt;include ref/&gt;
        FROM users
    &lt;/select&gt;
 
&lt;/mapper&gt;

explain

**<sql >**: Defines a SQL fragment named UserColumns, including the fields to be queried.

**<include ref/>**: In SQL queries for getUserById and getAllUsers methods, UserColumns are referenced through the <include> tag. This avoids repeated writing of the same field list and improves the maintainability of the code.

Optional properties

The <include> tag also supports some optional properties, such as parameterType and test, which can be used as needed.

Summarize

Using MyBatis' <include> tag, multiple SQL fragments can be effectively managed and reused, making the code clearer and easier to maintain.

The above is the detailed content of mybatis splicing dynamic sql through XML. For more information about mybatis splicing dynamic sql, please follow my other related articles!