动态SQL
动态SQL:就是根据不同的条件生成不同的SQL语句
如果你之前用过 JSTL 或任何基于类 XML 语言的文本处理器,你对动态 SQL 元素可能会感觉似曾相识。在 MyBatis 之前的版本中,需要花时间了解大量的元素。借助功能强大的基于 OGNL 的表达式,MyBatis 3 替换了之前的大部分元素,大大精简了元素种类,现在要学习的元素种类比原来的一半还要少。
- 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 '创建时间',
`view` int(30) NOT NULL COMMENT '浏览量'
)ENGINE=INNODB DEFAULT CHARSET=utf8
生成随机uid工具类
package com.shy.utils;
import java.util.UUID;
@SuppressWarnings("all")//抑制警告
public class IDutils {
public static String getId(){
return UUID.randomUUID().toString().replaceAll("-","");
}
}
创建一个基础工程
编写BlogMapper接口
package com.shy.dao;
import com.shy.pojo.Blog;
import java.util.List;
import java.util.Map;
public interface BlogMapper {
//插入树控件
int addBlog(Blog blog);
//更新博客
int updateBlog(Map map);
//查询博客
List<Blog> queryBlogIF(Map map);
List<Blog> queryBlogChoose(Map map);
//查询第1,2,3号记录的博客
List<Blog> queryBlogForeach(Map map);
}
实体类
@Data
public class Blog {
private int id;
private String title;
private String author;
private Date createTime;
private int views;
}
编写对应的xml文件并注册
<?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">
<!--configuration核心配置文件-->
<mapper namespace="com.shy.dao.BlogMapper">
<insert id="addBlog" parameterType="blog">
insert into blog (id,title,author,create_time,views)
values (#{id},#{title},#{author},#{createTime},#{views});
</insert>
<!--trim、where、set-->
<select id="queryBlogIF" 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>
<!--choose、when、otherwise-->
<select id="queryBlogChoose" parameterType="map" resultType="blog">
select * from blog
<where>
<choose>
<when test="title != null">
title = #{title}
</when>
<when test="author">
and author = #{author}
</when>
<otherwise>
and views = #{views}
</otherwise>
</choose>
</where>
</select>
<!--根据作者名字和博客名字来查询博客!如果作者名字为空,那么只根据博客名字查询,反之,则根据作者名来查询-->
<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>
<!--foreach-->
<select id="queryBlogForeach" 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" item="id" open="and (" close=")" separator="or">
id = #{id}
</foreach>
</where>
</select>
</mapper>

配置mybatis-config.xml
<!--引入外部配置文件:之前写过,直接拿来用-->
<properties resource="db.properties"/>
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
<!--是否开启驼峰命名自动映射,即从经典数据库列名 A_COLUMN 映射到经典 Java 属性名 aColumn。-->
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
<!--可以给实体类取别名-->
<typeAliases>
<package name="com.shy.pojo"/>
</typeAliases>
...
<mappers>
<mapper class="com.shy.dao.BlogMapper"/>
</mappers>
测试:
import com.shy.dao.BlogMapper;
import com.shy.pojo.Blog;
import com.shy.utils.IDutils;
import com.shy.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
public class MyTest {
@Test
public void test(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
Blog blog = new Blog();
blog.setId(IDutils.getId());
blog.setTitle("aaa");
blog.setAuthor("shy");
blog.setCreateTime(new Date());
blog.setViews(999);
mapper.addBlog(blog);
Blog blog2 = new Blog();
blog2.setId(IDutils.getId());
blog2.setTitle("bbbaaa");
blog2.setAuthor("hy");
blog2.setCreateTime(new Date());
blog2.setViews(999);
mapper.addBlog(blog2);
Blog blog3 = new Blog();
blog3.setId(IDutils.getId());
blog3.setTitle("我是aaa");
blog3.setAuthor("sy");
blog3.setCreateTime(new Date());
blog3.setViews(999);
mapper.addBlog(blog3);
sqlSession.commit();
sqlSession.close();
}
@Test
public void queryBlog(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap map = new HashMap();
//map.put("title","who");
map.put("author","shy2");
map.put("id","看数据表中生成的id,写上就行");
mapper.updateBlog(map);
sqlSession.commit();
sqlSession.close();
}
@Test
public void queryBlogForeach(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap map = new HashMap();
ArrayList<Integer> ids = new ArrayList<Integer>();
//这里由于生成的id过长,所以我直接修改了表中的id为123...
ids.add(1);
ids.add(2);
map.put("ids",ids);
List<Blog> blogs = mapper.queryBlogForeach(map);
for (Blog blog : blogs) {
System.out.println(blog);
}
sqlSession.close();
}
}
所谓的动态sql本质上还是sql语句,只是我们可以在sql层面可以执行一个逻辑代码
SQL片段
将一些功能的部分抽取出来,方便复用
1.使用sql标签抽取公共的部分
<sql id=""></sql>
2.在需要使用的地方用include标签引用即可
注意:
1.最好基于单表定义sql片段
2.标签内部不要存在where标签
动态sql就是在拼接sql语句,只要保证他的正确性,按照sql的格式,去排列组合就可以了。
先在Mysql中写出完整的sql,再对应的去修改动态sql实现通用
本文介绍MyBatis中动态SQL的应用,包括if、choose、foreach等元素的使用方法,并通过具体实例展示了如何构建灵活的SQL查询语句。

被折叠的 条评论
为什么被折叠?



