天天看點

MyBatis之動态SQL(if、where、set、choose、sql片段、foreach)

介紹
  • 動态SQL指的是根據不同的查詢條件 , 生成不同的Sql語句,也就是我們在jdbc代碼中的sql拼接工作
  • mybatis 動态SQL,通過 if, choose, when, otherwise, trim, where, set, foreach等标簽,可組合成非常靈活的SQL語句,進而在提高 SQL 語句的準确性的同時,也大大提高了開發人員的效率。
MyBatis之動态SQL(if、where、set、choose、sql片段、foreach)
搭建環境

1、搭建資料庫

字段:id,title,author,create_time,views

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、IDutil工具類

  • 通過UUID類生成随機數
public class IDUtil {

   public static String genId(){
       return UUID.randomUUID().toString().replaceAll("-","");
  }

}
           

3、實體類編寫 【注意set方法作用】

import java.util.Date;

public class Blog {

   private String id;
   private String title;
   private String author;
   private Date createTime;
   private int views;
   //set,get....
}
           

4、編寫Mapper接口及xml檔案

public interface BlogMapper {
}
<?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.yang.mapper.BlogMapper">

</mapper>
           

5、mybatis核心配置檔案

  • 配置set使下劃線駝峰自動轉換
<settings>
   <setting name="mapUnderscoreToCamelCase" value="true"/>
   <setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
<!--注冊Mapper.xml-->
<mappers>
 <mapper resource="mapper/BlogMapper.xml"/>
</mappers>
           

6、插入初始資料

  • 編寫接口
//新增一個部落格
int addBlog(Blog blog);
           
  • sql配置檔案
<insert id="addBlog" parameterType="blog">
  insert into blog (id, title, author, create_time, views)
  values (#{id},#{title},#{author},#{createTime},#{views});
</insert>
           
  • 初始化部落格
@Test
public void addInitBlog(){
   SqlSession session = MybatisUtils.getSession();
   BlogMapper mapper = session.getMapper(BlogMapper.class);

   Blog blog = new Blog();
   blog.setId(IDUtil.genId());
   blog.setTitle("鬥破蒼穹");
   blog.setAuthor("天蠶洋芋");
   blog.setCreateTime(new Date());
   blog.setViews(9999);

   mapper.addBlog(blog);

   blog.setId(IDUtil.genId());
   blog.setTitle("武動乾坤");
   mapper.addBlog(blog);

   blog.setId(IDUtil.genId());
   blog.setTitle("魔獸劍聖異界縱橫");
   mapper.addBlog(blog);

   blog.setId(IDUtil.genId());
   blog.setTitle("大主宰");
   mapper.addBlog(blog);

   session.close();
}
           
if 标簽

實作功能:根據作者名字和部落格名字來查詢部落格

1、編寫接口類

//需求1
List<Blog> queryBlogIf(Map map);
           

2、編寫SQL語句

<!--
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>
           

3、測試

  • 使用map傳遞兩個參數
@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","大主宰");
   map.put("author","天蠶洋芋");
   List<Blog> blogs = mapper.queryBlogIf(map);

   System.out.println(blogs);

   session.close();
}
           
  • 這裡當我們的書名為空時,sql語句就會出現錯誤了
  • 為了處理這種錯誤,我們就需要使用下面的where标簽
Where标簽
  • 同樣功能實作,可以将sql寫成如下
  • where标簽當有條件時自動插入where
  • where會自動删除多餘的and和or
<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>
           
Set标簽
  • set标簽功能相似where标簽,會自動幫我們增加set關鍵字

1、編寫接口方法

2、sql配置檔案

<!--注意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>
           

3、測試

@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","jjy的blog");
   map.put("author","jjy");
   map.put("id","123456789");
   mapper.updateBlog(map);
   session.close();
}
           
choose标簽
  • choose标簽隻會在下面的代碼中選擇一個分支進行
  • 相當于java代碼switch

1、編寫接口方法

2、sql配置檔案

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

3、測試類

@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","武動乾坤");
   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>
           
  • 引用SQL片段
<select id="queryBlogIf" parameterType="map" resultType="blog">
  select * from blog
   <where>
       <!-- 引用 sql 片段,如果refid 指定的不在本檔案中,那麼需要在前面加上 namespace -->
       <include refid="if-title-author"></include>
       <!-- 在這裡還可以引用其他的 sql 片段 -->
   </where>
</select>
           

注意

  • 最好基于單表來定義 sql片段,提高片段的可重用性
  • 在sql片段中不要包括 where
Foreach标簽

将資料庫中前三個資料的id修改為1,2,3

  • 我們需要查詢 blog 表中 id 分别為1,2,3的部落格資訊

1、編寫接口

2、編寫SQL語句

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

3、測試

@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();
}