动态 SQL 是指根据不同的条件生成不同的 SQL 语句
动态 SQL 详情请看链接
搭建环境:
mysql 建立博客表
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.编写实体类
4.编写实体类对应的 Mapper 接口和 Mapper.xml 文件
实体类:
package com.demo.pojo;import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;import java.util.Date;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Bolg {private String id;private String title;private String author;private Date createTime;private int views;
}
核心配置文件注册:
<mappers><mapper class="com.demo.dao.BlogMapper"/></mappers>
工具类:
package com.demo.utils;import org.junit.Test;import java.util.UUID;@SuppressWarnings("all") //抑制警告
public class IDutils {public static String getId(){//生成随机数return UUID.randomUUID().toString().replaceAll("-","");}@Testpublic void test(){System.out.println(IDutils.getId());}}
mapUnderscoreToCamelCase
是否开启驼峰命名自动映射,即从经典数据库列名 A_COLUMN 映射到经典 Java 属性名 aColumn
核心配置文件 settings 设置:
<settings><setting name="mapUnderscoreToCamelCase" value="true"/></settings>
接口:
package com.demo.dao;
import com.demo.pojo.Bolg;
public interface BlogMapper {//插入数据int addBlog(Bolg bolg);
}
mapper.xml 写 sql 语句:
<mapper namespace="com.demo.dao.BlogMapper"><insert id="addBlog" parameterType="com.demo.pojo.Bolg">insert into blog (id,title,author,create_time,views)values (#{id},#{title},#{author},#{createTime},#{views});</insert>
</mapper>
测试类:
package com.demo.dao;import com.demo.pojo.Bolg;
import com.demo.utils.IDutils;
import com.demo.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;import java.util.Date;public class MyTest {@Testpublic void addBlog(){SqlSession sqlSession = MybatisUtils.getSqlSession();BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);Bolg bolg = new Bolg();bolg.setId(IDutils.getId());bolg.setTitle("Mybatis");bolg.setAuthor("张三");bolg.setCreateTime(new Date());bolg.setViews(100);mapper.addBlog(bolg);bolg.setId(IDutils.getId());bolg.setTitle("Java");mapper.addBlog(bolg);bolg.setId(IDutils.getId());bolg.setTitle("Spring");mapper.addBlog(bolg);sqlSession.close();}
}
插入数据成功(设了日志)
if 语句:(实现精准搜索)
写个查询接口
public interface BlogMapper {//插入数据int addBlog(Bolg bolg);//查询博客List<Bolg> queryBlogIf(Map map);
}
mapper.xml:
<if test=" 非空 ">
and xx = #{xx}
</if>
实现查询语句的拼接
<select id="queryBlogIf" parameterType="map" resultType="com.demo.pojo.Bolg">select * from blog where 1=1<if test="title != null">and title = #{title}</if><if test="author != null">and author = #{author}</if></select>
测试:
new 一个 HashMap
通过 put 方法为查询语句拼接 title、author,指定二者的某条数据
即 select * from blog where title = "Java" and author = "张三";
@Testpublic void queryBlogIf() {SqlSession sqlSession = MybatisUtils.getSqlSession();BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);HashMap map = new HashMap();map.put("title","Java");map.put("author","张三");for (Bolg bolg : mapper.queryBlogIf(map)) {System.out.println(bolg);}sqlSession.close();}
可以看到查出一条数据
where 标签:
<select id="queryBlogIf" parameterType="map" resultType="com.demo.pojo.Bolg">select * from blog<where><if test="title != null">title = #{title}</if><if test="author != null">and author = #{author}</if></where></select>
choose 选择:多个条件中选择一个使用
写个接口:
List<Bolg> queryBlogChoose(Map map);
choose 标签和 when 标签配套
只要执行了第一个,后面就不执行
<select id="queryBlogChoose" parameterType="map" resultType="com.demo.pojo.Bolg">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>
测试类:
@Testpublic void queryBlogChoose() {SqlSession sqlSession = MybatisUtils.getSqlSession();BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);HashMap map = new HashMap();//map.put("title","Java");map.put("author","张三");map.put("views",100);for (Bolg bolg : mapper.queryBlogChoose(map)) {System.out.println(bolg);}sqlSession.close();}
运行结果:
set 标签:
set 元素会动态地在行首插入 SET 关键字,同时删掉额外的逗号
(这些逗号是在使用条件语句给列赋值时引入的)
写个接口:
//更新博客int updateBlog(Map map);
修改数据 sql:
<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>
自定义 trim 元素来定制 where 元素的功能
<trim prefix="WHERE" prefixOverrides="AND |OR ">...
</trim>
同理,prefix 前缀也可以是 SET
<trim prefix="SET" suffixOverrides=",">...
</trim>
所谓动态 SQL,本质上还是 SQL 语句
只是我们可以在 SQL 层面,去执行一个逻辑代码
需要复用时,可以使用 SQL 标签抽取公共部分,在需要使用的地方用 Include 标签引用即可
<sql id="xx"><if test="title != null">title = #{title}</if><if test="author != null">and author = #{author}</if></sql><select id="queryBlogIf" parameterType="map" resultType="com.demo.pojo.Bolg">select * from blog<where><include refid="xx"> </include></where></select>
foreach 标签:对集合进行遍历
指定一个集合,声明可以在元素体内使用的集合项(item)和索引(index)变量
它也允许你指定开头与结尾的字符串以及集合项迭代之间的分隔符
写个接口:
List<Bolg> queryBlogForeach();
map 可以存在一个集合
<!-- map可以存在一个集合 --><select id="queryBlogForeach" parameterType="map" resultType="com.demo.pojo.Bolg">select * from blog<where><foreach collection="ids" item="id" open="and (" close=")" separator="or">id = #{id}</foreach></where></select>
测试:
@Testpublic 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);ids.add(2);ids.add(3);map.put("ids",ids);for (Bolg bolg : mapper.queryBlogForeach(map)) {System.out.println(bolg);}sqlSession.close();}
可以看到执行的查询语句
动态 SQL 就是拼接 SQL 语句,只需保证 SQL 的正确性,按照 SQL 的格式排列组合即可