0%

6.动态SQL

6.什么是动态SQL

简单说就是根据不同的条件生成不同的SQL语句

1
2
3
4
5
6
动态 SQL 元素和 JSTL 或基于类似 XML 的文本处理器相似。在 MyBatis 之前的版本中,有很多元素需要花时间了解。MyBatis 3 大大精简了元素种类,现在只需学习原来一半的元素便可。MyBatis 采用功能强大的基于 OGNL 的表达式来淘汰其它大部分元素。

if
choose (when, otherwise)
trim (where, set)
foreach

搭建环境

创建一个工程

  • 导包

  • 编写配置文件

  • 编写实体类

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    package com.lwj.pojo;

    import java.util.Date;

    public class Blog {
    private int id;
    private String title;
    private String author;
    private Date create_time;
    private int views;

    ····
    ····
    ····
    get set 构造方法等这里为了节省文本就不再累述了
  • 实体类对应的Mapper接口和Mapper.xml
1
2
3
4
public interface BlogMapper {
//查询
List<Blog> queryBlogIf(Map map);
}
1
2
3
4
5
6
7
8
9
<select id="queryBlogIf" parameterType="map" resultType="com.lwj.pojo.Blog">
select * from blog where 1=1
<if test="title != null">
and title=#{title}
</if>
<if test="author != null">
and author=#{author}
</if>
</select>
  • 测试

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    @org.junit.Test
    public void test1() throws Exception{

    String resource = "mybatis-config.xml";
    InputStream inputStream = Resources.getResourceAsStream(resource);
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    SqlSession session = sqlSessionFactory.openSession();

    Map map = new HashMap();//如果map为空泽查询全部数据
    map.put("title","实施");

    List<Blog> list;
    list = session.selectList("com.lwj.dao.BlogMapper.queryBlogIf",map);
    for (Blog blog : list) {
    System.out.println(blog);
    }

    结果

    1
    2
    3
    4
    5

    Blog{id=2, title='实施', author='撒旦', create_time=Fri Feb 21 12:12:10 CST 2020, views=12}


    Process finished with exit code 0

IF

1
2
3
4
5
6
7
8
9
<select id="queryBlogIf" parameterType="map" resultType="com.lwj.pojo.Blog">
select * from blog where 1=1
<if test="title != null">
and title=#{title}
</if>
<if test="author != null">
and author=#{author}
</if>
</select>

choose, when, otherwise

有时我们不想应用到所有的条件语句,而只想从中择其一项。针对这种情况,MyBatis 提供了 choose 元素,它有点像 Java 中的 switch 语句。

就是把choose这个标签想象成switch就行了,满足第一个条件了就不会往下执行了,如果都不满足就看otherwise的条件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<select id="queryBlogChoose" parameterType="map" resultType="com.lwj.pojo.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>

trim, where, set

where 元素只会在至少有一个子元素的条件返回 SQL 子句的情况下才去插入“WHERE”子句。而且,若语句的开头为“AND”或“OR”,where 元素也会将它们去除。

where改造后的代码不需要再写where1=1

1
2
3
4
5
6
7
8
9
10
11
<select id="queryBlogIf" parameterType="map" resultType="com.lwj.pojo.Blog">
select * from blog
<where>
<if test="title != null">
and title=#{title}
</if>
<if test="author != null">
and author=#{author}
</if>
</where>
</select>