mybatis-动态sql

目录

1、简介

2、if语句

3、Where

4、Set

5、choose语句

6、SQL片段

7、Foreach


1、简介

        什么是动态SQL:动态SQL指的是根据不同的查询条件 , 生成不同的Sql语句

        我们之前写的 SQL 语句都比较简单,如果有比较复杂的业务,我们需要写复杂的 SQL 语句,往往需要拼接,而拼接 SQL ,稍微不注意,由于引号,空格等缺失可能都会导致错误。
        那么怎么去解决这个问题呢?这就要使用 mybatis 动态SQL,通过 if, choose, when, otherwise,trim, where, set, foreach等标签,可组合成非常灵活的SQL语句,从而在提高 SQL 语句的准确性的同时,也大大提高了开发人员的效率.

2、if语句

需求:根据作者名字和博客名字来查询博客!如果作者名字为空,那么只根据博客名字查询,反之,则根据作者名来查询

Mapper接口:

public interface BlogMapper {
    List<Blog> findBlogByIf(Map map);
}

Mapper.xml:

 <select id="findBlogByIf" 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>

 测试:

    @Test
    public void testIf(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        HashMap<String,Object> map=new HashMap<String, Object>();
        //map.put("title","java如此简单");
        map.put("author","rk说");
        List<Blog> blogByIf = mapper.findBlogByIf(map);
        for (Blog blog : blogByIf) {
            System.out.println(blog);
        }
        sqlSession.close();
    }

3、Where

        问题:如果后面的条件都不满足会报错:select * from blog where(sql语句不完整)

                如果第一个条件不满足,后面的条件满足会报错:        select  * from blog where and author=#{author}

<select id="findBlogByIf" resultType="blog" parameterType="map">
      select * from blog where
      <if test="title!=null">
          title=#{title}
      </if>
      <if test="author!=null">
          and author=#{author}
      </if>
</select>

        解决方法:使用Where标签

    <select id="findBlogByIf" resultType="blog" parameterType="map">
      select * from blog
     <where>
         <if test="title!=null">
             title=#{title}
         </if>
         <if test="author!=null">
             and author=#{author}
         </if>
     </where>
    </select>

        Where 元素只会在至少一个子元素的条件返回SQL子句的情况下才会插入一个‘where’子句。此外,如果标签返回的内容是以AND 或OR 开头的,则它会剔除掉

4、Set

        同理,上面的对于查询 SQL 语句包含 where 关键字,如果在进行更新操作的时候,含有 set 关键词,我们怎么处理呢?

mapper:

   int updateBlog(Map map);

mapper.xml:

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

        这里的set 标签会动态的前置SET关键字,同时也会删除无关的逗号。比如上面这个,第一个if成立,sql为 update blog title=#{title}, where id =#{id}  这里多了一个逗号

测试:

    @Test
    public void testSet(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        HashMap<String,Object> map=new HashMap<String, Object>();
        map.put("title","java如此简单");
        map.put("id","1");
        int i = mapper.updateBlog(map);
        sqlSession.close();
    }

5、choose语句

        有时候,我们不想用到所有的查询条件,只想选择其中的一个,查询条件有一个满足即可,使用 choose标签可以解决此类问题,类似于 Java 的 switch 语句

mapper:

List<Blog> findBlogChoose(Map map);

mapper.xml:

<select id="findBlogChoose" 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 testChoose(){
        SqlSession session = MybatisUtils.getSqlSession();
        BlogMapper mapper = session.getMapper(BlogMapper.class);
        HashMap<String, Object> map = new HashMap<String, Object>();
       // map.put("title","java如此单");
        map.put("author","rk说");
       // map.put("views",9999);
        List<Blog> blogs = mapper.findBlogChoose(map);
        System.out.println(blogs);
        session.close();
    }

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

        注意:1、最好基于 单表来定义 sql 片段,提高片段的可重用性
                   2、在 sql 片段中不要包括 where

7、Foreach

        将数据库中前三个数据的id修改为1,2,3;
        需求:我们需要查询 blog 表中 id 分别为1,2,3的博客信息

mapper:

    List<Blog> findBlogForeach(List<Integer> list);

mapper.xml:

  <select id="findBlogForeach" resultType="blog" parameterType="list">
        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="list" item="id" open="and ("
                     separator="or"  close=")">
                id=#{id}
            </foreach>
        </where>
    </select>

测试:

    @Test
    public void testForeach(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        List<Integer> list=new LinkedList<Integer>();
        list.add(1);
        list.add(2);
        list.add(3);
        List<Blog> blogForeach = mapper.findBlogForeach(list);
        for (Blog foreach : blogForeach) {
            System.out.println(foreach);
        }
        sqlSession.close();
    }

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Rk..

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值