Table of Contents
choose" >choose
set" >set
foreach tag can be iterated Generate a series of values" >##foreachforeach tag can be iterated Generate a series of values
Home Database SQL Learn MyBatis dynamic SQL

Learn MyBatis dynamic SQL

Dec 09, 2020 pm 05:46 PM
mybatis sql

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;}
Copy after login

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))
Copy after login

if

Define interface method

public List<User> findByUser(User user);
Copy after login

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

<select id="findByUser" resultType="com.example.mybatis.entity.User">
    select
    id, username, user_email userEmail, user_city userCity, age
    from user
    where    <if test="username != null and username != &#39;&#39;">
        username = #{username}    </if>
    <if test="userEmail != null and userEmail != &#39;&#39;">
        and user_email = #{userEmail}    </if>
    <if test="userCity != null and userCity != &#39;&#39;">
        and user_city = #{userCity}    </if></select>
Copy after login

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 = ?
Copy after login

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 = ?
Copy after login

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 = ?
Copy after login

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 id="findByUser" resultType="com.example.mybatis.entity.User">
        select
        id, username, user_email userEmail, user_city userCity, age        from user
        <where>
            <if test="username != null and username != &#39;&#39;">
                username = #{username}
            </if>
            <if test="userEmail != null and userEmail != &#39;&#39;">
                and user_email = #{userEmail}
            </if>
            <if test="userCity != null and userCity != &#39;&#39;">
                and user_city = #{userCity}
            </if>
        </where>
    </select>
Copy after login

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 id="findByUser" resultType="com.example.mybatis.entity.User">
        select
        id, username, user_email userEmail, user_city userCity, age
        from user        <trim prefix="where" prefixOverrides="and">
            <if test="username != null and username != &#39;&#39;">
                username = #{username}            </if>
            <if test="userEmail != null and userEmail != &#39;&#39;">
                and user_email = #{userEmail}            </if>
            <if test="userCity != null and userCity != &#39;&#39;">
                and user_city = #{userCity}            </if>
        </trim>
    </select>
Copy after login
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}
Copy after login
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}
Copy after login
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 id="findByUser" resultType="com.example.mybatis.entity.User">
        select
        id, username, user_email userEmail, user_city userCity, age
        from user        <where>
            <choose>
                <when test="username != null and username != &#39;&#39;">
                    username = #{username}                </when>
                <when test="userEmail != null and userEmail != &#39;&#39;">
                    and user_email = #{userEmail}                </when>
                <when test="userCity != null and userCity != &#39;&#39;">
                    and user_city = #{userCity}                </when>
            </choose>
        </where>
    </select>
Copy after login
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);
Copy after login
The Mapper.xml definition corresponding to the interface is as follows

<update id="updateUser" parameterType="com.example.mybatis.entity.User">
       update user       <set>
           <if test="username != null and username != &#39;&#39;">
               username=#{username},           </if>
           <if test="userEmail != null and userEmail != &#39;&#39;">
               user_email=#{userEmail},           </if>
           <if test="userCity != null and userCity != &#39;&#39;">
               user_city=#{userCity},           </if>
           <if test="age != null">
              age=#{age}           </if>
       </set>
       where id=#{id}    </update>
Copy after login

*

for use in SQL in statements*

接口定义如下所示

public List<User> getUsersByIds(List<Integer> ids);
Copy after login

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

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

用于批量插入

接口定义如下所示

public int addUserList(List<User> users);
Copy after login

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

<insert id="addUserList"
        parameterType="com.example.mybatis.entity.User">
    insert into user
    (username, user_email, user_city, age)
    values    <foreach item="user"  collection="list" separator=",">
        (#{user.username}, #{user.userEmail}, #{user.userCity}, #{user.age})    </foreach></insert><!--返回自增主键--><insert id="addUserList"
        parameterType="com.example.mybatis.entity.User"
        useGeneratedKeys="true"
        keyProperty="id">
    insert into user
    (username, user_email, user_city, age)
    values    <foreach item="user"  collection="list" separator=",">
        (#{user.username}, #{user.userEmail}, #{user.userCity}, #{user.age})    </foreach></insert><!--还可以这样写--><!--
    这种方式需要数据库连接属性设置allowMultiQueries=true
    这种分号分隔多个SQL还可以用于其他的批量操作,如修改、删除
--><insert id="addUserList"
        parameterType="com.example.mybatis.entity.User">
    <foreach item="user"  collection="list" separator=";">
        insert into user
        (username, user_email, user_city, age)
        values
        (#{user.username}, #{user.userEmail}, #{user.userCity}, #{user.age})    </foreach></insert><!--如果是Oracle数据库,则需要这样写--><insert id="addUserList"
        parameterType="com.example.mybatis.entity.User">
    <foreach item="user" open="begin" close="end;"  collection="list">
        insert into user
        (username, user_email, user_city, age)
        values
        (#{user.username}, #{user.userEmail}, #{user.userCity}, #{user.age});    </foreach></insert>
Copy after login

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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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 ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What is the difference between HQL and SQL in Hibernate framework? What is the difference between HQL and SQL in Hibernate framework? Apr 17, 2024 pm 02:57 PM

HQL and SQL are compared in the Hibernate framework: HQL (1. Object-oriented syntax, 2. Database-independent queries, 3. Type safety), while SQL directly operates the database (1. Database-independent standards, 2. Complex executable queries and data manipulation).

Usage of division operation in Oracle SQL Usage of division operation in Oracle SQL Mar 10, 2024 pm 03:06 PM

"Usage of Division Operation in OracleSQL" In OracleSQL, division operation is one of the common mathematical operations. During data query and processing, division operations can help us calculate the ratio between fields or derive the logical relationship between specific values. This article will introduce the usage of division operation in OracleSQL and provide specific code examples. 1. Two ways of division operations in OracleSQL In OracleSQL, division operations can be performed in two different ways.

Comparison and differences of SQL syntax between Oracle and DB2 Comparison and differences of SQL syntax between Oracle and DB2 Mar 11, 2024 pm 12:09 PM

Oracle and DB2 are two commonly used relational database management systems, each of which has its own unique SQL syntax and characteristics. This article will compare and differ between the SQL syntax of Oracle and DB2, and provide specific code examples. Database connection In Oracle, use the following statement to connect to the database: CONNECTusername/password@database. In DB2, the statement to connect to the database is as follows: CONNECTTOdataba

Detailed explanation of the Set tag function in MyBatis dynamic SQL tags Detailed explanation of the Set tag function in MyBatis dynamic SQL tags Feb 26, 2024 pm 07:48 PM

Interpretation of MyBatis dynamic SQL tags: Detailed explanation of Set tag usage MyBatis is an excellent persistence layer framework. It provides a wealth of dynamic SQL tags and can flexibly construct database operation statements. Among them, the Set tag is used to generate the SET clause in the UPDATE statement, which is very commonly used in update operations. This article will explain in detail the usage of the Set tag in MyBatis and demonstrate its functionality through specific code examples. What is Set tag Set tag is used in MyBati

How to solve the 5120 error in SQL How to solve the 5120 error in SQL Mar 06, 2024 pm 04:33 PM

Solution: 1. Check whether the logged-in user has sufficient permissions to access or operate the database, and ensure that the user has the correct permissions; 2. Check whether the account of the SQL Server service has permission to access the specified file or folder, and ensure that the account Have sufficient permissions to read and write the file or folder; 3. Check whether the specified database file has been opened or locked by other processes, try to close or release the file, and rerun the query; 4. Try as administrator Run Management Studio as etc.

MyBatis Generator configuration parameter interpretation and best practices MyBatis Generator configuration parameter interpretation and best practices Feb 23, 2024 am 09:51 AM

MyBatisGenerator is a code generation tool officially provided by MyBatis, which can help developers quickly generate JavaBeans, Mapper interfaces and XML mapping files that conform to the database table structure. In the process of using MyBatisGenerator for code generation, the setting of configuration parameters is crucial. This article will start from the perspective of configuration parameters and deeply explore the functions of MyBatisGenerator.

Database technology competition: What are the differences between Oracle and SQL? Database technology competition: What are the differences between Oracle and SQL? Mar 09, 2024 am 08:30 AM

Database technology competition: What are the differences between Oracle and SQL? In the database field, Oracle and SQL Server are two highly respected relational database management systems. Although they both belong to the category of relational databases, there are many differences between them. In this article, we will delve into the differences between Oracle and SQL Server, as well as their features and advantages in practical applications. First of all, there are differences in syntax between Oracle and SQL Server.

Detailed explanation of MyBatis first-level cache: How to improve data access efficiency? Detailed explanation of MyBatis first-level cache: How to improve data access efficiency? Feb 23, 2024 pm 08:13 PM

Detailed explanation of MyBatis first-level cache: How to improve data access efficiency? During the development process, efficient data access has always been one of the focuses of programmers. For persistence layer frameworks like MyBatis, caching is one of the key methods to improve data access efficiency. MyBatis provides two caching mechanisms: first-level cache and second-level cache. The first-level cache is enabled by default. This article will introduce the mechanism of MyBatis first-level cache in detail and provide specific code examples to help readers better understand

See all articles