Mybatis-12-动态SQL

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

如果你之前用过 JSTL 或任何基于类 XML 语言的文本处理器,你对动态 SQL 元素可能会感觉似曾相识。在 MyBatis 之前的版本中,需要花时间了解大量的元素。借助功能强大的基于 OGNL 的表达式,MyBatis 3 替换了之前的大部分元素,大大精简了元素种类,现在要学习的元素种类比原来的一半还要少。 ​
if 
choose (when, otherwise)
trim (where, set)
foreach

10.1、搭建环境

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
  1. 导包

  2. 编写配置文件

  3. 编写实体类

    @Data
    public class blog {
        private String id;
        private String title;
        private String author;
        private Date createtime;
        private int views;
    }
  4. 编写实体类对应的Mapper接口及xml文件

    @SuppressWarnings("all")
    public interface blogMapper {
        blog get();
        int addblog(blog blog);
        List<blog> getblogIF(Map map);
        List<blog> getblogCHOOSE(Map map);
        int updateblog(Map map);
        List<blog> getblogforeach(Map map);
    }
  5.  测试

10.2、if

使用动态 SQL 最常见情景是根据条件包含 where 子句的一部分。

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

注意:

  • if标签不能单独使用,只能跟在where后面或者放在where标签内

测试:

@Test
public void  testif(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    blogMapper mapper = sqlSession.getMapper(blogMapper.class);
    Map map = new HashMap();
   // map.put("title","Java如此简单2");
    map.put("author","小墨sang");
    //map.put("views",9999);
    //map.put("id","028bed7fba4a49b09c6265eba5774a56");
    List<blog> blogs = mapper.getblogIF(map);
​
    for (blog blog : blogs) {
        System.out.println(blog);
    }
    sqlSession.close();
}

10.3、choose(when、otherwise)

有时候,我们不想用到所有的查询条件,只想选择其中的一个,查询条件有一个满足即可。

使用 choose 标签可以解决此类问题,类似于 Java 的 switch 语句

<select id="getblogCHOOSE" 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 test4(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    blogMapper mapper = sqlSession.getMapper(blogMapper.class);
    Map map=new HashMap();
    map.put("title","Java如此简单2");
    System.out.println(mapper.getblogCHOOSE(map));
​
}

10.4、trim(where、set)

如果将 “where 1=1’” 设置成动态条件

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

如果没有匹配的条件会怎么样?最终这条 SQL 会变成这样:

SELECT * FROM BLOG 
WHERE

这会导致查询失败。如果匹配的只是第二个条件又会怎样?这条 SQL 会是这样:

SELECT * FROM BLOG
WHERE
AND title like ‘someTitle’

MyBatis 有一个简单且适合大多数场景的解决办法。而在其他场景中,可以对其进行自定义以符合需求。

where 元素只会在子元素返回任何内容的情况下才插入 “WHERE” 子句。

而且,若子句的开头为 “AND” 或 “OR”,where 元素也会将它们去除。

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

同理,上面的对于查询 SQL 语句包含 where 关键字,如果在进行更新操作的时候,含有 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>

动态SQL本质还是SQL语句,只是我们可以在SQL层面执行一个逻辑代码

10.5、SQL片段

有时候可能某个 sql 语句我们用的特别多,为了增加代码的重用性,简化代码,我们需要将这些代码抽取出来,然后使用时直接调用。

  1. 使用sql标签抽取公共的部分

    <sql id="if">
        <if test="title!=null">
            title=#{title}
        </if>
        <if test="author!=null">
            and author=#{author}
        </if>
    </sql>
  2. 在需要使用的地方使用includei标签引用

    <select id="getblogIF" parameterType="map" resultType="blog">
            select * from blog
            <where>
               <include refid="if"></include>
            </where>

注意:

  • 最好基于单表来定义SQL片段

  • 不要存在where标签

10.6、foreach

需求:

select * from blog where 1=1 and (id=1 or id=2 or id=3)

Mapper.xml

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

测试

@Test
public void test3(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    blogMapper mapper = sqlSession.getMapper(blogMapper.class);
    HashMap map = new HashMap();
    ArrayList<Integer> list = new ArrayList<>();
    list.add(1);
    list.add(2);
    map.put("ids",list);
​
    List<blog> li = mapper.getblogforeach(map);
    for (blog blog : li) {
        System.out.println(blog);
    }
    sqlSession.close();
}

动态SQL本质就是在拼接SQL语句,我们只要保证SQL的正确性,按照SQL的格式,去排列组合即可。

建议:

  • 为了保证拼接准确,首先写原生的 sql 语句,然后在通过 mybatis 动态sql 对照着改

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值