Mybatis:动态SQL详解

33 阅读3分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第29天,点击查看活动详

概述

什么是动态SQL标签: L?

根据不同的条件生成不同的SQL语句

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

动态SQL标签:

if

choose (when, otherwise)

trim (where, set)

foreach

案例实战

搭建数据库环境

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

创建Maven环境

导入依赖

    <!--  导入依赖-->
    <dependencies>
        <!--导入mysql驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
    <!--  导入mybatis驱动      -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>
        <!--导入junit依赖-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.10</version>
            <scope>provided</scope>
        </dependency>

编写全局配置文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<!--核心配置文件-->
<configuration>

<!--  引入外部配置文件  优先使用外部引用 -->
    <properties resource="db.properties" />

<!--    设置-->
<settings>
<!--   标准的日志工厂实现-->
    <setting name="logImpl" value="STDOUT_LOGGING" />
    <setting name="mapUnderscoreToCamelCase" value="true" />
</settings>

<!--给实体类起别名-->
    <typeAliases>
<!--        <typeAlias type="com.zhao.pojo.User" alias="User"></typeAlias>-->
        <package name="com.zhao.pojo"/>
    </typeAliases>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>

<!--    绑定接口-->
    <mappers>
       <mapper class="com.zhao.dao.BlogMapper"></mapper>
    </mappers>
</configuration>

编写实体类

@Data
public class Blog {

    private String id;
    private String title;
    private String author;
    //属性名和字段名不一致
    private Date createTime;
    private int views;

}

编写持久层接口

public interface BlogMapper {

    //插入数据
    int addBlog(Blog blog);

    //查询
    List<Blog> queryBlogIF(Map map);

    //查询
    List<Blog> queryBlogChoose(Map map);

    //更新
    int updateBlog(Map map);

    //查询第1,2,3id的博客
    List<Blog> queryBlogForeach(Map map);

}

编写接口对应的Mapper配置文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--核心配置文件-->
<mapper namespace="com.zhao.dao.BlogMapper">

</mapper>

IF标签

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

测试一下

public void queryBlogIF() {
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
    Map map = new HashMap();
    //map.put("title","Java");
    map.put("author", "狂神说");
    List<Blog> blogList = mapper.queryBlogIF(map);
    for (Blog blog : blogList) {
        System.out.println(blog);
    }
    sqlSession.close();
}

image.png

choose (when, otherwise)标签

<select id="queryBlogChoose" parameterType="map" resultType="blog">
    select * from mybatis.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>

测试一下

public void queryBlogChoose() {
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
    Map map = new HashMap();
    map.put("title", "Java");
    map.put("author", "哈哈");
    map.put("id", 2);
    //map.put("views",9999);
    List<Blog> blogList = mapper.queryBlogChoose(map);
    for (Blog blog : blogList) {
        System.out.println(blog);
    }
    sqlSession.close();
}

image.png

trim (set)

<update id="updateBlog" parameterType="map">
    update mybatis.blog
    <set>
        <if test="title !=null">
            title=#{title},
        </if>
        <if test="author !=null">
            author=#{author}
        </if>
    </set>
    where id=#{id};
</update>

测试一下

public void updateBlog() {
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
    Map map = new HashMap();
    //map.put("title", "Java如此简单");
    map.put("author", "小赵");
    map.put("id", "1");
    mapper.updateBlog(map);

    sqlSession.commit();
    sqlSession.close();
}

image.png

Foreach标签

foreach 元素的功能非常强大,它允许你指定一个集合,声明可以在元素体内使用的集合项(item)和索引(index)变量。它也允许你指定开头与结尾的字符串以及集合项迭代之间的分隔符。

<select id="queryBlogForeach" parameterType="map" resultType="blog">
    select * from blog
    <where>
        <foreach collection="ids" item="id" open="and (" separator="or" close=")">
            id=#{id}
        </foreach>
    </where>
</select>

测试一下

public void queryBlogForeach(){
    SqlSession sqlSession=MybatisUtils.getSqlSession();
    BlogMapper mapper=sqlSession.getMapper(BlogMapper.class);
    HashMap map=new HashMap();
    ArrayList<Integer> ids=new ArrayList<Integer>();
    ids.add(1);

    map.put("ids",ids);
    List<Blog> blogList=mapper.queryBlogForeach(map);
    for (Blog blog : blogList) {
        System.out.println(blog);
    }
    sqlSession.close();
}

image.png

SQL片段

在实际的很多场景下,我们需要将重复的sql抽离出来成为一个公共的部分,让其他的场景进行复用,达到避免造轮子的效果。Mybatis中提供了一个SQL片段的标签可以满足以上的场景。

第一步:使用SQL片段抽离SQL

<sql id="if-title-author">
    <if test="title != null">
        and title=#{title}
    </if>
    <if test="author !=null">
        and author=#{author}
    </if>
</sql>

第二步:使用Include标签引用即可

<select id="queryBlogIF" parameterType="map" resultType="blog">
    select * from mybatis.blog
    <where>
        <include refid="if-title-author"></include>
    </where>
</select>

注意事项:

  • 最好基于单表来定义SQL片段
  • 不要存在where标签

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