[MyBatis]—dynamic SQL (configuration file method)

scene:

     When we use JDBC or other similar frameworks for database development, we usually need to manually assemble SQL according to the needs. It is a very painful thing to think about, and the function of dynamic assembly of SQL statements provided by the Mybatis framework can be very convenient. Good solution to this trouble.

Overview:

     Dynamic SQL is a powerful feature of the MyBatis framework. MyBatis3 can use powerful OGNL-based expressions to complete dynamic SQL. It removes most of the elements that need to be understood in previous versions, and can be completed with less than half of the original elements. required work.

SQL element:

SQL elements illustrate
<if> Judgment statement, used for single conditional branch judgment
<choose>  (<when>,<otherwise>) Equivalent to switch...case...default statement in Java, used for multi-conditional branch judgment
<where> Simplify the conditional judgment of where in SQL statements
<trim> Can flexibly remove redundant keywords
<set> Resolving dynamic update statements
<foreach> Loop statements, often used in enumeration conditions such as in statements
<bind> Create a variable from an OGNL expression and bind it to the context, commonly used in SQL for fuzzy queries

<if>:

The most common scenario for using dynamic SQL is to include part of a where clause based on a condition

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.example.mapper.BookMapper">

    <resultMap id="BookType" type="org.example.po.Book">
        <id property="id" column="id"></id>
        <result property="bookName" column="bookName"></result>
        <result property="price" column="price"></result>
        <result property="publisher" column="publisher"></result>
    </resultMap>

    <select id="bookSelectById" parameterType="int" resultMap="BookType">
        select * from t_book
        <where>
            <if test="id!=null and id!=''">
                id=#{id}
            </if>
        </where>
    </select>

    <select id="bookSelectByname" parameterType="string" resultMap="BookType">
        select * from t_book
        <where>
            <if test="bookNmae!=null and bookName!=''">
                bookName LIKE concat('%',#{bookName},'%')
            </if>
        </where>
    </select>

</mapper>

<choose>:

      Sometimes, we don't want to use all the conditions, but just want to use one of multiple conditions. For this situation, MyBatis provides the choose element, which is a bit like a switch statement in Java.

Because I wrote a single query, I quoted the official website code.

<select id="findActiveBlogLike"
     resultType="Blog">
  SELECT * FROM BLOG WHERE state = ‘ACTIVE’
  <choose>
    <when test="title != null">
      AND title like #{title}
    </when>
    <when test="author != null and author.name != null">
      AND author_name like #{author.name}
    </when>
    <otherwise>
      AND featured = 1
    </otherwise>
  </choose>
</select>

<where>:

     The <where> tag is equivalent to where 1=1, which is mainly used to simplify the where condition judgment in SQL statements, and can intelligently handle and and or without worrying about syntax errors caused by redundant keywords. Code reference <if> tag code.

<trim>:

      I think this tag is the most flexible. The trim element will also automatically identify whether there is a return value in its tag. If so, it will add some prefix or suffix to the contained content (first determine whether there is a statement containing ), the properties used are

 1.    prefix (prefix), suffix (suffix)

You can also remove the symbols that contain the first or last content of the content. The attributes used are

2 , prefixOverride (prefix coverage), suffixOverride (suffix coverage)

It can be said that the function is very powerful, and it can be used to replace the where element and achieve the same effect as the where element.

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.example.mapper.BookMapper">

    <resultMap id="BookType" type="org.example.po.Book">
        <id property="id" column="id"></id>
        <result property="bookName" column="bookName"></result>
        <result property="price" column="price"></result>
        <result property="publisher" column="publisher"></result>
    </resultMap>

    <update id="bookUpdate" parameterType="book">
        UPDATE t_book
        <trim prefix="set" suffixOverrides=",">
            <if test="bookName!=null and bookName!=''">bookName=#{bookName},</if>
            <if test="price!=null and price!=''">price=#{price},</if>
            <if test="publisher!=null and publisher!=''">publisher=#{publisher}</if>
            WHERE id=#{id}
        </trim>
    </update>

</mapper>

<set>:

      The set element is mainly used for update operations. Its main function is similar to that of the where element. It is mainly to enter a set before the contained statement. If the contained statement ends with a comma, the parentheses will be automatically ignored , and the if element can be used to dynamically Update the fields that need to be modified; if the fields do not need to be changed, they can no longer be updated.

Modify the above code to:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.example.mapper.BookMapper">

    <resultMap id="BookType" type="org.example.po.Book">
        <id property="id" column="id"></id>
        <result property="bookName" column="bookName"></result>
        <result property="price" column="price"></result>
        <result property="publisher" column="publisher"></result>
    </resultMap>

    <update id="bookUpdate" parameterType="book">
        UPDATE t_book
<!--        <trim prefix="set" suffixOverrides=",">-->
<!--            <if test="bookName!=null and bookName!=''">bookName=#{bookName},</if>-->
<!--            <if test="price!=null and price!=''">price=#{price},</if>-->
<!--            <if test="publisher!=null and publisher!=''">publisher=#{publisher}</if>-->
<!--            WHERE id=#{id}-->
<!--        </trim>-->
        <set>
            <if test="bookName!=null and bookName!=''">bookName=#{bookName},</if>
            <if test="price!=null and price!=''">price=#{price},</if>
            <if test="publisher!=null and publisher!=''">publisher=#{publisher},</if>
        </set>
        WHERE id=#{id}
    </update>


</mapper>

<foreach>:

The foreach element is usually used when building an in conditional statement, and it is used as follows.

(1).  item : Represents the alias of each element when iterating.

(2).  index : Specify a name to indicate the position of each iteration in the iteration process

(3).  open : Indicates what the statement starts with (the in statement starts with "( ")

(4).  separator : Indicates that the above symbol is used as the separator each time it is iterated (the in statement uses "," as the separator)

(5).  close : Indicates what the statement ends with (the in statement ends with " )")

(Note: This open, separator, and close are basically fixed formats)

(6).  collection : Indicates the most critical and error-prone properties, and needs special attention. This attribute must be specified. The value of this attribute is different in different cases. There are three main cases:

        1). If the input parameter is a single parameter and the parameter type is a list , the value of the collection attribute is list

        2). If the input parameter is a single parameter and the parameter type is an array , the collection attribute value is array

        3). If the input parameter is multi-parameter , it needs to be encapsulated as a Map for processing

Format:

<select id="selectPostIn" resultType="domain.blog.Post">
  SELECT *
  FROM POST P
  <where>
    <foreach item="item" index="id" collection="list"
        open="ID in (" separator="," close=")" nullable="true">
          #{item}
    </foreach>
  </where>
</select>

<bind>:

   The bind element is usually used in a statement that requires a fuzzy query. The bind element is used to define a variable named pattern_username, and the attribute value of value is the concatenated query string, where _parameter.getTitle() represents the parameter passed in (or Directly write the corresponding parameter variable name, such as username).

<select id="selectBlogsLike" resultType="Blog">
  <bind name="pattern_username" value="'%' + _parameter.getTitle() + '%'" />
  SELECT * FROM BLOG
  WHERE title LIKE #{pattern}
</select>

Guess you like

Origin blog.csdn.net/m0_56233309/article/details/123547225