mybatis學習 動態sql記錄
阿新 • • 發佈:2020-12-19
十二、動態SQL
什麼是動態SQL
動態SQL就是指根據不同的條件生成不同的SQL語句
- if
- choose (when, otherwise)
- trim (where, set)
- foreach
搭建環境
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
@lombok.Data
public class Blog {
private int id;
private String title;
private String author;
private Data createTime;
private int views;
}
IF
<select id="queryBlog" resultType="blog" parameterType="map">
select * from 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 blog
<where>
<choose>
<when test="title != null">
title = #{title}
</when>
<when test="author != title">
AND author = #{author}
</when>
<otherwise>
and views = #{views}
</otherwise>
</choose>
</where>
</select>
trim (where, set)
where 元素只會在子元素返回任何內容的情況下才插入 “WHERE” 子句。而且,若子句的開頭為 “AND” 或 “OR”,where 元素也會將它們去除。
<select id="queryBlog" resultType="blog" parameterType="map">
select * from blog
<where>
<if test="title != null">
and title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</where>
</select>
foreach
foreach 元素的功能非常強大,它允許你指定一個集合,宣告可以在元素體內使用的集合項(item)和索引(index)變數。它也允許你指定開頭與結尾的字串以及集合項迭代之間的分隔符。這個元素也不會錯誤地新增多餘的分隔符
<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>
提示 你可以將任何可迭代物件(如 List、Set 等)、Map 物件或者陣列物件作為集合引數傳遞給 foreach。當使用可迭代物件或者陣列時,index 是當前迭代的序號,item 的值是本次迭代獲取到的元素。當使用 Map 物件(或者 Map.Entry 物件的集合)時,index 是鍵,item 是值。
SQL片段
有的時候,會將一些公共部分抽取出來,方便複用
<sql id="if-title-author">
<if test="title != null">
and title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</sql>
<select id="queryBlog" resultType="blog" parameterType="map">
select * from blog
<where>
<include refid="if-title-author"/>
</where>
</select>
注意事項:
- 最好基於單表來定義SQL片段
- 不要存在where標籤