天天看点

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