Explain the Mybatis series (9) --- Powerful dynamic SQL

http://www.cnblogs.com/dongying/p/4092662.html

The last article " Mybatis series (eight) --- mapper mapping file configuration select, resultMap " briefly introduced the query of mybatis, so far, CRUD has been finished. This article will introduce the powerful dynamic SQL of mybatis.

So, here comes the question: What is dynamic SQL? What does dynamic SQL do?

  In the traditional method of using JDBC, I believe that when you combine complex SQL statements, you need to splicing them. The dynamic SQL function of Mybatis is to solve this problem. It can be combined into very flexible SQL statements through the if, choose, when, otherwise, trim, where, set, and foreach tags, thereby improving the efficiency of developers. Let's feel the charm of Mybatis dynamic SQL:

 

1. if: You can judge, so can I!

As a programmer, who doesn't understand if! You can also use if in mybatis:

copy code
<select id="findUserById" resultType="user">
           select * from user where
           <if test="id != null">
               id=#{id}
           </if>
            and deleteFlag=0;
</select>
copy code

The above example: If the incoming id is not empty, then the SQL will splicing id = #{id}. I believe that everyone can understand this by looking at it, not much to say.

Careful people will find a problem: "You are wrong! If the id you pass in is null, then your final SQL statement will become select * from user where and deleteFlag=0, there is a problem with this statement!"

Yes, at this time, the where tag of mybatis should make a grand debut:

 

2. where, with me, SQL statement splicing conditions are all clouds!

Let's transform the above example through where:

copy code
<select id="findUserById" resultType="user">
           select * from user
           <where>
               <if test="id != null">
                   id=#{id}
               </if>
               and deleteFlag=0;
           </where>
 </select>
copy code

Some people are about to ask: "What are you doing! Compared with the above, isn't there an extra where tag! Will this one still appear select * from user where and deleteFlag=0 ?"

Indeed, on the surface, it is just an extra where tag, but in essence, mybatis processes it. When it encounters AND or OR, it knows how to deal with it. In fact, we can customize this processing rule through the trim tag.

 

3. trim : My site, I call the shots!

The above where tag, in fact, the trim can be expressed as follows:

<trim prefix="WHERE" prefixOverrides="AND |OR ">
  ...
</trim>

It means: When WHERE is followed by AND or OR, remove AND or OR. In addition to WHERE, there is actually a more classic implementation, that is SET.

 

4. set: trust me, no mistakes!

copy code
<update id="updateUser" parameterType="com.dy.entity.User">
           update user set
           <if test="name != null">
               name = #{name},
           </if> 
           <if test="password != null">
               password = #{password},
           </if> 
           <if test="age != null">
               age = #{age}
           </if> 
           <where>
               <if test="id != null">
                   id = #{id}
               </if>
               and deleteFlag = 0;
           </where>
</update>
copy code

问题又来了: “如果我只有name不为null,  那么这SQL不就成了 update set name = #{name}, where ........ ?  你那name后面那逗号会导致出错啊!”

是的,这时候,就可以用mybatis为我们提供的set 标签了。下面是通过set标签改造后:

copy code
<update id="updateUser" parameterType="com.dy.entity.User">
           update user
        <set>
          <if test="name != null">name = #{name},</if> 
             <if test="password != null">password = #{password},</if> 
             <if test="age != null">age = #{age},</if> 
        </set>
           <where>
               <if test="id != null">
                   id = #{id}
               </if>
               and deleteFlag = 0;
           </where>
</update>
copy code

这个用trim 可表示为:

<trim prefix="SET" suffixOverrides=",">
  ...
</trim>

WHERE是使用的 prefixOverrides(前缀), SET是使用的 suffixOverrides (后缀), 看明白了吧!

 

5. foreach:  你有for, 我有foreach, 不要以为就你才屌!

java中有for, 可通过for循环, 同样, mybatis中有foreach, 可通过它实现循环,循环的对象当然主要是java容器和数组。

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

将一个 List 实例或者数组作为参数对象传给 MyBatis,当这么做的时候,MyBatis 会自动将它包装在一个 Map 中并以名称为键。List 实例将会以“list”作为键,而数组实例的键将是“array”。同样, 当循环的对象为map的时候,index其实就是map的key。

 

6. choose:  我选择了你,你选择了我!

Java中有switch,  mybatis有choose。

copy 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>
copy code

In the above example: when both title and author are not null, then choose one of the two (the former is preferred), if both are null, then choose otherwise, if only one of tilte and author is not null, then choose The one that is not null.

Looking at the dynamic SQL of mybatis, it is powerful and simple. I believe you can use it with a simple look.

Alright, that's it for this time! The next article will combine the source code of mybatis to analyze the whole process of executing a sql statement.


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326072387&siteId=291194637