12、動態SQL
阿新 • • 發佈:2020-12-31
什麼是動態SQL?
動態 SQL 是 MyBatis 的強大特性之一。例如拼接時要確保不能忘記新增必要的空格,還要注意去掉列表最後一個列名的逗號。利用動態 SQL,可以徹底擺脫這種痛苦。
如果你之前用過 JSTL 或任何基於類 XML 語言的文字處理器,你對動態 SQL 元素可能會感覺似曾相識。在 MyBatis 之前的版本中,需要花時間瞭解大量的元素。藉助功能強大的基於 OGNL 的表示式,MyBatis 3 替換了之前的大部分元素,大大精簡了元素種類,現在要學習的元素種類比原來的一半還要少。
- if
- choose (when, otherwise)
- trim (where, set)
- foreach
基礎工程:
1、建立sql
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
2、導包
3、建立pojo實體類
@Data @AllArgsConstructor @NoArgsConstructor public class Blog { private int id; private String title; private String author; private Date create_time; private int views; }
4、編寫實體類對應mapper介面 和 mapper.xml檔案
=========================測試====================================
Where、if
提供了可選的查詢文字功能。
where 元素只會在子元素返回任何內容的情況下才插入 “WHERE” 子句。
而且,若子句的開頭為 “AND” 或 “OR”,where 元素也會將它們去除。
<select id="selBlogIf" resultType="blog" parameterType="map">
/*1=1是為了讓if為false的情況下能把所有的記錄查出來*/
select * from blog
<where>
<if test="title != null">
and title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</where>
</select>
@Test public void selBlogIfTest(){ SqlSession sqlSession = MybatisUtil.getSqlSession(); BlogMapper mapper = sqlSession.getMapper(BlogMapper.class); Map map = new HashMap(); map.put("title","Java"); List<Blog> blogs = mapper.selBlogIf(map); for (Blog blog : blogs) { System.out.println(blog); } sqlSession.close(); }
添加了title的值,說明上面發判斷為true,就能查出來:title = "java"的記錄
choose、when、otherwise
有時候,我們不想使用所有的條件,而只是想從多個條件中選擇一個使用。針對這種情況,MyBatis 提供了 choose 元素,它有點像 Java 中的 switch 語句。
- 匹配順序是從第一個進行選擇,第一個成立就執行第一個中的匹配,
- 如果第一個第二個資料都匹配的話,還是按第一個中的執行
- 所有條件不匹配就會執行otherwise
<select id="selBlogIf" resultType="blog" parameterType="map"> select * from blog <where> <choose> <when test="author != null"> and author = #{author} </when> <when test="title != null"> and title = #{title} </when> <otherwise> and views = #{views} </otherwise> </choose> </where> </select>
where、set
- set 元素會動態地在行首插入 SET 關鍵字,並會刪掉額外的逗號(這些逗號是在使用條件語句給列賦值時引入的)。
<update id="updateBlog" parameterType="map"> update blog <set> <if test="author != null"> author = #{author} </if> </set> <where> <if test="id != null"> id = #{id} </if> </where> </update>
@Test public void updateBlogIfTest(){ SqlSession sqlSession = MybatisUtil.getSqlSession(); BlogMapper mapper = sqlSession.getMapper(BlogMapper.class); Map map = new HashMap(); map.put("id","4bdfaea75d5c416fb2c10a6d4c51cf8f"); map.put("author","zhangzhixi"); mapper.updateBlog(map); sqlSession.commit(); sqlSession.close(); }
修改成功!