search
HomeDatabaseSQLLearn MyBatis dynamic SQL

Learn MyBatis dynamic SQL

Dec 09, 2020 pm 05:46 PM
mybatissql

sql tutorialIntroducing the powerful features of SQL MyBatis SQL

Learn MyBatis dynamic SQL

Recommended (free): sql tutorial

Dynamic SQL

One of the powerful features of MyBatis is its dynamic SQL. If you have experience using JDBC or other similar frameworks, you will understand the pain of splicing SQL statements based on different conditions. For example, when splicing, make sure not to forget to add necessary spaces, and be careful to remove the comma from the last column name in the list. Take advantage of the dynamic SQL feature to get rid of this pain completely.

Although it was not easy to use dynamic SQL in the past, MyBatis improved this situation by providing a powerful dynamic SQL language that can be used in any SQL mapping statement.

Dynamic SQL elements are similar to JSTL or XML-based text processors. In previous versions of MyBatis, there were many elements that took time to understand. MyBatis 3 has greatly simplified the types of elements. Now you only need to learn half of the original elements. MyBatis uses powerful OGNL-based expressions to eliminate most other elements.

Preparation

First create the User entity class

public class User {
    private Integer id;
    private String username;
    private String userEmail;
    private String userCity;
    private Integer age;}

Create the user table

CREATE TABLE user (
  id int(11) NOT NULL AUTO_INCREMENT,
  username varchar(255) DEFAULT NULL,
    user_email varchar(255) DEFAULT NULL,
    user_city varchar(255) DEFAULT NULL,
    age int(11) DEFAULT NULL,
  PRIMARY KEY (id))

if

Define interface method

public List<user> findByUser(User user);</user>

The definition of Mapper.xml corresponding to the interface is as follows

<select>
    select
    id, username, user_email userEmail, user_city userCity, age
    from user
    where    <if>
        username = #{username}    </if>
    <if>
        and user_email = #{userEmail}    </if>
    <if>
        and user_city = #{userCity}    </if></select>

If the test on the if tag is true, then the SQL statement in the if tag will be Splicing.

If username, userEmail, and userCity are not empty, then the SQL will be spliced ​​as shown below

select id, username, user_email userEmail, user_city userCity, age 
from user where username = ? and user_email = ? and user_city = ?

If only username is not empty, then the SQL will be spliced ​​as shown below

select id, username, user_email userEmail, user_city userCity, age 
from user where username = ?

However, there is a disadvantage in this method. Assume that username is empty at this time, userEmail and userCity are not empty.

Let's analyze the dynamic SQL code. Now there is no value assigned to username, that is, username==null, so the "username=#{username}" code will not be added to the SQL statement, so the final spliced Dynamic SQL is like this:

select id, username, user_email userEmail, user_city userCity, age 
from user where and user_email = ? and user_city = ?

where is directly followed by and, which is an obvious syntax error. At this time, the and that follows where should be deleted. . To solve this problem, you can use the where tag.

#where

Change the above SQL to the following

    <select>
        select
        id, username, user_email userEmail, user_city userCity, age        from user
        <where>
            <if>
                username = #{username}
            </if>
            <if>
                and user_email = #{userEmail}
            </if>
            <if>
                and user_city = #{userCity}
            </if>
        </where>
    </select>

ifwhere##if inside the tag If the tag meets the conditions, then the where tag will be spliced ​​into a where statement. If the SQL spliced ​​with the if tag has an and statement at the front, then the and will be spliced ​​into a where statement. delete. Using this method, unnecessary keywords in SQL will be automatically deleted, so generally if tags and where tags are used in combination. The prefix

and

suffix attributes in the

trimtrim tag will be used to generate The actual SQL statement will be spliced ​​with the statement inside the label.

If the values ​​specified in the

prefixOverrides or suffixOverrides attributes are encountered before or after the statement, MyBatis will automatically delete them. When specifying multiple values, don't forget to have a space after each value to ensure that it will not be connected with subsequent SQL.

prefix: Add a prefix to the spliced ​​SQL statement

suffix: Add a suffix to the spliced ​​SQL statement

prefixOverrides: If prefixOverrides is encountered before the spliced ​​SQL statement, MyBatis will automatically delete them

suffixOverrides: If it is encountered after the spliced ​​SQL statement suffixOverrides, MyBatis will automatically delete them

Use the

trim tag below to implement the function of the where tag

<select>
        select
        id, username, user_email userEmail, user_city userCity, age
        from user        <trim>
            <if>
                username = #{username}            </if>
            <if>
                and user_email = #{userEmail}            </if>
            <if>
                and user_city = #{userCity}            </if>
        </trim>
    </select>
if username is empty, userEmail and userCity are not empty, then the SQL statement of

if label splicing is as follows

and user_email = #{userEmail} and user_city = #{userCity}
Because the

trim label is set with prefixOverrides="and" , and the above SQL statement has an and statement in front of it, so the above and statement needs to be deleted, and because the trim tag is set with prefix="where", it is necessary to add a where statement in front of the spliced ​​SQL statement.

Finally

trimThe SQL statement of the tag is spliced ​​as follows

where user_email = #{userEmail} and user_city = #{userCity}
Sometimes we don’t want to apply to all conditional statement, but only want to select one of them. For this situation, MyBatis provides the choose element, which is a bit like the switch statement in Java.

<select>
        select
        id, username, user_email userEmail, user_city userCity, age
        from user        <where>
            <choose>
                <when>
                    username = #{username}                </when>
                <when>
                    and user_email = #{userEmail}                </when>
                <when>
                    and user_city = #{userCity}                </when>
            </choose>
        </where>
    </select>
set tag is used for Update operation and will automatically generate SQL statements based on parameter selection.

The interface is defined as follows

public int updateUser(User user);
The Mapper.xml definition corresponding to the interface is as follows

<update>
       update user       <set>
           <if>
               username=#{username},           </if>
           <if>
               user_email=#{userEmail},           </if>
           <if>
               user_city=#{userCity},           </if>
           <if>
              age=#{age}           </if>
       </set>
       where id=#{id}    </update>

*

for use in SQL in statements*

接口定义如下所示

public List<user> getUsersByIds(List<integer> ids);</integer></user>

接口对应的 Mapper.xml 定义如下所示

<!--
        collection: 指定要遍历的集合
            默认情况下
                如果为Collection类型的,key为collection;
                如果为List类型的,key为list
                如果是数组类型,key为array
            可以通过@Param("ids")来指定key
        item: 将当前遍历的元素赋值给指定的变量
        open: 给遍历的结果添加一个开始字符
        close: 给遍历的结果添加一个结束字符
        separator: 每个元素之间的分隔符
    --><select>
    select * from user
    where id in    <foreach>
        #{id}    </foreach></select>

用于批量插入

接口定义如下所示

public int addUserList(List<user> users);</user>

接口对应的 Mapper.xml 定义如下所示

<insert>
    insert into user
    (username, user_email, user_city, age)
    values    <foreach>
        (#{user.username}, #{user.userEmail}, #{user.userCity}, #{user.age})    </foreach></insert><!--返回自增主键--><insert>
    insert into user
    (username, user_email, user_city, age)
    values    <foreach>
        (#{user.username}, #{user.userEmail}, #{user.userCity}, #{user.age})    </foreach></insert><!--还可以这样写--><!--
    这种方式需要数据库连接属性设置allowMultiQueries=true
    这种分号分隔多个SQL还可以用于其他的批量操作,如修改、删除
--><insert>
    <foreach>
        insert into user
        (username, user_email, user_city, age)
        values
        (#{user.username}, #{user.userEmail}, #{user.userCity}, #{user.age})    </foreach></insert><!--如果是Oracle数据库,则需要这样写--><insert>
    <foreach>
        insert into user
        (username, user_email, user_city, age)
        values
        (#{user.username}, #{user.userEmail}, #{user.userCity}, #{user.age});    </foreach></insert>

The above is the detailed content of Learn MyBatis dynamic SQL. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:learnku. If there is any infringement, please contact admin@php.cn delete
SQL for Data Analysis: Advanced Techniques for Business IntelligenceSQL for Data Analysis: Advanced Techniques for Business IntelligenceApr 14, 2025 am 12:02 AM

Advanced query skills in SQL include subqueries, window functions, CTEs and complex JOINs, which can handle complex data analysis requirements. 1) Subquery is used to find the employees with the highest salary in each department. 2) Window functions and CTE are used to analyze employee salary growth trends. 3) Performance optimization strategies include index optimization, query rewriting and using partition tables.

MySQL: A Specific Implementation of SQLMySQL: A Specific Implementation of SQLApr 13, 2025 am 12:02 AM

MySQL is an open source relational database management system that provides standard SQL functions and extensions. 1) MySQL supports standard SQL operations such as CREATE, INSERT, UPDATE, DELETE, and extends the LIMIT clause. 2) It uses storage engines such as InnoDB and MyISAM, which are suitable for different scenarios. 3) Users can efficiently use MySQL through advanced functions such as creating tables, inserting data, and using stored procedures.

SQL: Making Data Management Accessible to AllSQL: Making Data Management Accessible to AllApr 12, 2025 am 12:14 AM

SQLmakesdatamanagementaccessibletoallbyprovidingasimpleyetpowerfultoolsetforqueryingandmanagingdatabases.1)Itworkswithrelationaldatabases,allowinguserstospecifywhattheywanttodowiththedata.2)SQL'sstrengthliesinfiltering,sorting,andjoiningdataacrosstab

SQL Indexing Strategies: Improve Query Performance by Orders of MagnitudeSQL Indexing Strategies: Improve Query Performance by Orders of MagnitudeApr 11, 2025 am 12:04 AM

SQL indexes can significantly improve query performance through clever design. 1. Select the appropriate index type, such as B-tree, hash or full text index. 2. Use composite index to optimize multi-field query. 3. Avoid over-index to reduce data maintenance overhead. 4. Maintain indexes regularly, including rebuilding and removing unnecessary indexes.

How to delete constraints in sqlHow to delete constraints in sqlApr 10, 2025 pm 12:21 PM

To delete a constraint in SQL, perform the following steps: Identify the constraint name to be deleted; use the ALTER TABLE statement: ALTER TABLE table name DROP CONSTRAINT constraint name; confirm deletion.

How to set SQL triggerHow to set SQL triggerApr 10, 2025 pm 12:18 PM

A SQL trigger is a database object that automatically performs specific actions when a specific event is executed on a specified table. To set up SQL triggers, you can use the CREATE TRIGGER statement, which includes the trigger name, table name, event type, and trigger code. The trigger code is defined using the AS keyword and contains SQL or PL/SQL statements or blocks. By specifying trigger conditions, you can use the WHERE clause to limit the execution scope of a trigger. Trigger operations can be performed in the trigger code using the INSERT INTO, UPDATE, or DELETE statement. NEW and OLD keywords can be used to reference the affected keyword in the trigger code.

How to add index for SQL queryHow to add index for SQL queryApr 10, 2025 pm 12:15 PM

Indexing is a data structure that accelerates data search by sorting data columns. The steps to add an index to an SQL query are as follows: Determine the columns that need to be indexed. Select the appropriate index type (B-tree, hash, or bitmap). Use the CREATE INDEX command to create an index. Reconstruct or reorganize the index regularly to maintain its efficiency. The benefits of adding indexes include improved query performance, reduced I/O operations, optimized sorting and filtering, and improved concurrency. When queries often use specific columns, return large amounts of data that need to be sorted or grouped, involve multiple tables or database tables that are large, you should consider adding an index.

How to use ifelse sql statementHow to use ifelse sql statementApr 10, 2025 pm 12:12 PM

The IFELSE statement is a conditional statement that returns different values ​​based on the conditional evaluation result. Its syntax structure is: IF (condition) THEN return_value_if_condition_is_true ELSE return_value_if_condition_is_false END IF;.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft