前言:
什么是动态sql? 在sql层面通过条件语句去拼接sql,
本文涉及mybatis动态标签有 where set if when foreach SQl片段 缓存(主要)
一,环境搭建
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
2,导包
3,编写实体类
package com.king.pojo; import lombok.Data; import java.util.Date; @Data public class Blog { private String id; private String title; private String author; private Date createTime; private int views; }
4,搭建实体类对应的mapper接口和mapper.xml
package com.king.dao; public interface BlogMapper { }
<?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.king.dao.BlogMapper">
</mapper>
5 动态sql 的mapper接口和mapper.xml
5.1 if
//if(动态sql练习) List<Blog> queryBlogIf(Map map);
<select id="queryBlogIf" parameterType="map" resultType="blog"> select * from mybatis.blog WHERE 1=1 <if test="title !=null"> and title=#{title} </if> <if test="author !=null"> and author=#{author} </if> </select>
5.2 choose (when,otherwise)
注意:因为属于choose,所以动态拼接时只会选择第一个满足要求的,这跟if标签本质上的区别
<select id="queryBlogChoose" parameterType="map" resultType="blog"> select * from mybatis.blog <where> <choose> <when test="title !=null"> and title=#{title} </when> <otherwise > and author=#{author} </otherwise> </choose> </where> </select>
5.3,trim(where,set)
5.3.1 where标签
<select id="queryBlogIf" parameterType="map" resultType="blog"> select * from mybatis.blog <where> <!--where代替了sql的where,当where中都不满足,就执行原始sql-->
<!--里面填写if,when等动态sql标签-->
</where> </select>
were总结:动态前置WHERE,同时将sql语句中多余的and删除掉
5.3.2 set标签
作用:动态前置SET关键词,同时将sql语句中无关的逗号删除掉
<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>
6.sql片段
本质:与封装特性相似,将sql中重复率高的语句拿出来封装成一个片段,对外留出一个接口(id),sql语句仅需搭配 where 使用<include refid="id名字">就可使用,
注意事项:最好基于单表查询,因为多表查询时重复效率变低,且容易出错
不要存在where标签
7,foreach(遍历)
7.1官网解释
7.2 练习
sql原语句
SELECT * from blog where (id=1 or id=2 or id=3)
mybatis实现
<select id="getBlogListByForeach" parameterType="map" resultType="blog"> select * from mybatis.blog <where> <foreach collection="ids" item="id" open="and (" close=")" separator="or"> id=#{id} </foreach> </where> </select>