1. 程式人生 > 資料庫 >MyBatis 動態SQL!

MyBatis 動態SQL!

12、動態SQL

什麼是動態SQL:動態SQL就是指根據不同的條件生成不同的SQL語句

利用動態 SQL,可以徹底擺脫這種痛苦。

如果你之前用過 JSTL 或任何基於類 XML 語言的文字處理器,你對動態 SQL 元素可能會感覺似曾相識。在 MyBatis 之前的版本中,需要花時間瞭解大量的元素。藉助功能強大的基於 OGNL 的表示式,MyBatis 3 替換了之前的大部分元素,大大精簡了元素種類,現在要學習的元素種類比原來的一半還要少。

if
choose (when, otherwise)
trim (where, set)
foreach

搭建環境(20-12-23)

CREATE TABLE `blog`(
`id` VARCHAR(50) NOT NULL COMMENT '部落格id',
`title` VARCHAR(100) NOT NULL COMMENT '部落格標題',
`author` VARCHAR(30) NOT NULL COMMENT '部落格作者',
`create_time` DATETIME NOT NULL COMMENT '建立時間',
`views` INT(30) NOT NULL COMMENT '瀏覽量'
)ENGINE=INNODB DEFAULT CHARSET=utf8

建立一個基礎工程

  1. 導包(Lombok可選)

  2. 編寫配置檔案

  3. 編寫實體類

    public class Blog {
        private int id;
        private String title;
        private String author;
        private Date createTime;
        private int views;
    }
    
  4. 編寫實體類對應的Mapper介面 和 Mapper.xml檔案

    public interface BlogMapper {
    
        //插入資料
        int addBlog(Blog blog);
    }
    
    <mapper namespace="com.kuang.dao.BlogMapper">
        <insert id="addBlog" parameterType="blog">
            insert into mybatis.blog (id, title, author, create_time, views)
            values (#{id},#{title},#{author},#{createTime},#{views})
        </insert>
    </mapper>
    

IF

<select id="queryBlogIF" parameterType="map" resultType="blog">
    select * from mybatis.blog where 1=1
    <if test="title != null">
       and title = #{title}
    </if>
    <if test="author != null">
        and author = #{author}
    </if>
</select>

choose (when, otherwise)

<select id="queryBlogChoose" parameterType="map" resultType="blog">
    select * from mybatis.blog
    <where>
        <choose>
            <when test="title != null">
                title = #{title}
            </when>
            <when test="author != null">
                and author=#{author}
            </when>
            <otherwise>
                and views = #{views}
            </otherwise>
        </choose>
    </where>
</select>

trim (where, set)

<select id="queryBlogIF" parameterType="map" resultType="blog">
    select * from mybatis.blog
    #         where 1=1
    <where>
        <if test="title != null">
            title = #{title}
        </if>
        <if test="author != null">
            and author = #{author}
        </if>
    </where>
</select>
<update id="updateBlog" parameterType="map">
    update mybatis.blog
    <set>
        <if test="title!=null">
            title = #{title},
        </if>
        <if test="author!=null">
            author = #{author}
        </if>
    </set>
    where id=#{id}
</update>

所謂的動態SQL,本質還是SQL語句,只是我們可以在SQL層面,去執行一個邏輯程式碼

if

where , set , choose , when