MyBatis dynamic SQL first chapter of the multi-criteria query (if, where, trim label)

A dynamic SQL Overview

Previously, when using JDBC operational data, particularly if the query will be concatenated into the SQL string condition is a painful thing. The usual solution is to write a lot of if-else conditional statement string stitching, and make sure not to forget spaces or to omit a comma in the field. MyBatis uses dynamic SQL to improve this situation, dynamic SQL is based on an expression OGNL can help us achieve some logic in SQL statements . Elements for realizing the following dynamic SQL.

  • if: use simple terms if selected
  • choose (when, otherwise): the equivalent of a switch statement in Java , and otherwise generally used when match
  • set: solve the dynamic update statement
  • trim: the flexibility to remove excess keyword
  • foreach: a collection of iterations, typically used in conditions

Two, if usage

In the query conditions are not numerous and relatively fixed, the best solution is to use multiple parameters directly into the parameters manner, so that the code is relatively clear, readable. as follows

public interface UserMappper{
    public List<User> getUserList(@Param("userName") String userName,
                                  @Param("userRole") Integer roleId);
}
<select id="getUserList" resultMap="userList">
  select u.*, r.roleName from smbms_user u, smbms_role r
  where u.userName like connect ('%', #{userName}, '%')
  and u.userRole=#{userRole} and u.userRole=r.id
</select>

In the above code, the parameters used @Param annotations, and rename userRole parameters roleId

Codes described above were tested as follows

  • In the case where both conditions are given, such as a String userName = "Sun"; Integer roleId = 3, the correct result is output at this time;
  • If the incoming user role roleId is empty, that only by user name fuzzy query, such as String userName = "Sun"; Integer roleId = null, then the output of the result does not satisfy the requirements: no input user roles only be demand fuzzy query based on user name;
  • If the incoming user is the user name userName "" (the empty string), roleId has the value (roleId = 3), this time the result is correct;

In response to these user input such a field may be empty case, if we use dynamic SQL elements to achieve multi-criteria query, as follows

<select id="getUserList" resultMap="userList">
  select u.*, r.roleName from smbms_user u, smbms_role r where u.userRole=r.id
    <if test="userRole != null">
      and u.userRole = #{userRole}
    </if>
    <if test="userName != null and userName != ''">
      and u.userName like concat('%', #{userName}, '%')
    </if>
</select>

In the above code using a simple if element condition judgment, if Test element attribute indicates if the entry conditions are satisfied the needs. At this time, for String userName = "Sun"; Integer roleId = null this case, the output of the correct result.

Three, if + where usage

Single-table queries, consider the following code

<select id="getUserList" resultType="User">
  select * from smbms_user where
    <if test="userName != null and userName != ''">
      u.userName like concat('%', #{userName}, '%')
    </if>
    <if test="userRole != null">
      and u.userRole = #{userRole}
    </if>
</select>

At this time, for String userName = ""; Integer roleId = 3 case, being given, because of a more "and".

For this process and, where, you can use dynamic SQL where elements, where the element is mainly used to simplify the conditions where the SQL statement to judge, and intelligent processing and and or, do not worry about grammatical errors caused unnecessary keywords. as follows

<select id="getUserList" resultType="User">
  select * from smbms_user
    <where>
      <if test="userName != null and userName != ''">
        and u.userName like concat('%', #{userName}, '%')
      </if>
      <if test="userRole != null">
        and u.userRole = #{userRole}
      </if>
    </where>
</select> 

where element tags will automatically return a value identifying whether its label, if any, where a is inserted. In addition, if the contents of the tag is returned and or or beginning, it will be automatically removed. At this time, for String userName = ""; Integer roleIdthis case will be output correctly

Four, if + trim usage

Except where elements can also be used to replace trim elements where the elements, and where element to achieve the same effect.

trim element will automatically recognize whether a tag within its return value , if the return value, the self-contained content before adding some prefix, some may follow it with a suffix, a prefix corresponding attribute and suffix; trim may also comprise the contents of header cover some of the content (i.e., ignored), or some of the content of the tail cover, the corresponding attribute is prefixOverrieds and suffixOverrieds.

<select id="getUserList" resultType="User">
  select * from smbms_user
  <trim prefix="where" prefixOverrides="and | or">
    <if test="userName != null and userName != ''">
      and u.userName like concat('%', #{userName}, '%')
    </if>
    <if test="userRole != null">
      and u.userRole = #{userRole}
    </if>
  </trim>
</select>

prefixOverrides: specifying the content for the header trim with content Ignore

Guess you like

Origin www.cnblogs.com/yanguobin/p/11708254.html