Mybatis全解-06
動態SQL
什麼是動態SQL
通過if,choose,when,otherwise,trim,where,set,foreach等標籤,可自由組合成非常靈活的SQL語句,從而在提高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 NOTNULL COMMENT '建立時間', `views` int(30) NOT NULL COMMENT '瀏覽量' ) ENGINE=InnoDB DEFAULT CHARSET=utf8
UUID工具類,大量使用
public class IDUtil { public static String genId(){ return UUID.randomUUID().toString().replaceAll("-",""); } }
編寫對應的實體類
import java.util.Date; public class Blog { privateString id; private String title; private String author; private Date createTime; private int views; //set,get.... }
編寫Mapper介面及對應的xml檔案
public interface BlogMapper { //新增一個部落格 int addBlog(Blog blog); } <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC"-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.li.mapper.BlogMapper"> <insert id="addBlog" parameterType="blog"> insert into blog (id, title, author, create_time, views) values (#{id},#{title},#{author},#{createTime},#{views}); </insert> </mapper>
編寫mybatis核心配置檔案,下劃線駝峰自動轉換
<settings> <setting name="mapUnderscoreToCamelCase" value="true"/> <setting name="logImpl" value="STDOUT_LOGGING"/> </settings> <!--註冊Mapper.xml--> <mappers> <mapper resource="mapper/BlogMapper.xml"/> </mappers>
插入資料,初始化部落格
@Test public void addInitBlog(){ SqlSession session = MybatisUtils.getSession(); BlogMapper mapper = session.getMapper(BlogMapper.class); Blog blog = new Blog(); blog.setId(IDUtil.genId()); blog.setTitle("Mybatis如此簡單"); blog.setAuthor("李扶搖"); blog.setCreateTime(new Date()); blog.setViews(9999); mapper.addBlog(blog); blog.setId(IDUtil.genId()); blog.setTitle("Java如此簡單"); mapper.addBlog(blog); blog.setId(IDUtil.genId()); blog.setTitle("Spring如此簡單"); mapper.addBlog(blog); blog.setId(IDUtil.genId()); blog.setTitle("微服務如此簡單"); mapper.addBlog(blog); session.close(); }
需求:根據作者名字和部落格名字來查詢部落格,如果作者名字為空,那麼只根據部落格名字查詢,反之,則根據作者名來查詢。
<if>
//需求1 List<Blog> queryBlogIf(Map map);
<!--需求1: 根據作者名字和部落格名字來查詢部落格! 如果作者名字為空,那麼只根據部落格名字查詢,反之,則根據作者名來查詢 select * from blog where title = #{title} and author = #{author} --> <select id="queryBlogIf" parameterType="map" resultType="blog"> select * from blog where <if test="title != null"> title = #{title} </if> <if test="author != null"> and author = #{author} </if> </select>
@Test public void testQueryBlogIf(){ SqlSession session = MybatisUtils.getSession(); BlogMapper mapper = session.getMapper(BlogMapper.class); HashMap<String, String> map = new HashMap<String, String>(); map.put("title","Mybatis如此簡單"); map.put("author","李扶搖"); List<Blog> blogs = mapper.queryBlogIf(map); System.out.println(blogs); session.close(); }
這樣寫我們可以看到,如果 author 等於 null,那麼查詢語句為 select * from user where title=#{title},但是如果title為空呢?那麼查詢語句為 select * from user where and author=#{author},這是錯誤的 SQL 語句,如何解決呢?使用where標籤!
<where>
<select id="queryBlogIf" parameterType="map" resultType="blog"> select * from blog <where> <if test="title != null"> title = #{title} </if> <if test="author != null"> and author = #{author} </if> </where> </select>
這個“where”標籤會知道如果它包含的標籤中有返回值的話,它就插入一個‘where’。此外,如果標籤返回的內容是以AND 或OR 開頭的,則它會剔除掉。
<set>
int updateBlog(Map map);
<!--注意set是用的逗號隔開--> <update id="updateBlog" parameterType="map"> update blog <set> <if test="title != null"> title = #{title}, </if> <if test="author != null"> author = #{author} </if> </set> where id = #{id}; </update>
@Test public void testUpdateBlog(){ SqlSession session = MybatisUtils.getSession(); BlogMapper mapper = session.getMapper(BlogMapper.class); HashMap<String, String> map = new HashMap<String, String>(); map.put("title","動態SQL"); map.put("author","小張"); map.put("id","9d6a763f5e1347cebda43e2a32687a77"); mapper.updateBlog(map); session.close(); }
<choose>
有時候,我們不想用到所有的查詢條件,只想選擇其中的一個,查詢條件有一個滿足即可,使用 choose 標籤可以解決此類問題,類似於 Java 的 switch 語句。
<select id="queryBlogChoose" parameterType="map" resultType="blog"> select * from 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>
@Test public void testQueryBlogChoose(){ SqlSession session = MybatisUtils.getSession(); BlogMapper mapper = session.getMapper(BlogMapper.class); HashMap<String, Object> map = new HashMap<String, Object>(); map.put("title","Java如此簡單"); map.put("author","李扶搖"); map.put("views",9999); List<Blog> blogs = mapper.queryBlogChoose(map); System.out.println(blogs); session.close(); }
SQL片段
有時候可能某個 sql 語句我們用的特別多,為了增加程式碼的重用性,簡化程式碼,我們需要將這些程式碼抽取出來,然後使用時直接呼叫。類似於工具類。
<sql>
<sql id="if-title-author"> <if test="title != null"> title = #{title} </if> <if test="author != null"> and author = #{author} </if> </sql>
<include>引用
<select id="queryBlogIf" parameterType="map" resultType="blog"> select * from blog <where> <!-- 引用 sql 片段,如果refid 指定的不在本檔案中,那麼需要在前面加上 namespace --> <include refid="if-title-author"></include> <!-- 在這裡還可以引用其他的 sql 片段 --> </where> </select>
<foreach>
需求:我們需要查詢 blog 表中 id 分別為1,2,3的部落格資訊
List<Blog> queryBlogForeach(Map map);
<select id="queryBlogForeach" parameterType="map" resultType="blog"> select * from blog <where> <!-- collection:指定輸入物件中的集合屬性 item:每次遍歷生成的物件 open:開始遍歷時的拼接字串 close:結束時拼接的字串 separator:遍歷物件之間需要拼接的字串 select * from blog where 1=1 and (id=1 or id=2 or id=3) --> <foreach collection="ids" item="id" open="and (" close=")" separator="or"> id=#{id} </foreach> </where> </select>
@Test public void testQueryBlogForeach(){ SqlSession session = MybatisUtils.getSession(); BlogMapper mapper = session.getMapper(BlogMapper.class); HashMap map = new HashMap(); List<Integer> ids = new ArrayList<Integer>(); ids.add(1); ids.add(2); ids.add(3); map.put("ids",ids); List<Blog> blogs = mapper.queryBlogForeach(map); System.out.println(blogs); session.close(); }
小結:其實動態 sql 語句的編寫往往就是一個拼接的問題,為了保證拼接準確,我們最好首先要寫原生的 sql 語句出來,然後在通過 mybatis 動態sql 對照著改,防止出錯。多在實踐中使用才是熟練掌握它的技巧。