文章目录
我们之前写的 SQL 语句都比较简单,如果有比较复杂的业务,我们需要写复杂的 SQL 语句,往往需要拼接,而拼接 SQL ,稍微不注意,由于引号,空格等缺失可能都会导致错误。
那么怎么去解决这个问题呢?这就要使用 mybatis 动态SQL,通过 if, choose, when, otherwise, trim, where, set, foreach等标签,可组合成非常灵活的SQL语句,从而在提高 SQL 语句的准确性的同时,也大大提高了开发人员的效率。
通过动态标签,来实现动态链接,SQL在开发中大量使用,所以一定要熟练掌握
1.if标签 :满足条件时,if标签才会链接
2.where标签:它包含标签中有返回值的话,它就会插入一个where,如果标签返回内容是以AND或OR开头的话,则它会剔除掉
3.set标签:在至少有一个子元素返回了SQL语句时,才会向SQL语句中添加SET,并且如果SET之后是以,开头的话,会自动将其删掉
4.choose标签:有时候用不到所有的查询条件,只想选择其中的一个,查询条件有一个满足即可,使用choose标签可以满足
5.SQL片段:有时候可以通过将部分代码抽出来作为公用,使用时候可以直接调用
6.Foreach:对集合进行遍历
1.前提工作
需知:不太熟悉的小伙伴可以查看以往博客内容
1.Mybatis环境搭建
2.Mybatis标签解读以及增删改查的实现
3.表单处理-一对多和多对一
2.构建并搭建完毕项目
1.在数据库中创建一个blog表单
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.idea创建一个maven项目:
3.配置pom依赖和mybatis核心配置
pom中依赖导入:
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.12</version>
</dependency>
<dependency>
<groupId>org.example</groupId>
<artifactId>mybatis_test5</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
</dependencies>
mybatis.xml中环境配置:
<?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>
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
<environments default="mysql">
<environment id = "mysql">
<transactionManager type="JDBC"></transactionManager>
<dataSource type = "POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/bobo?useSSL=false&useUnicode=true&characterEncoding=utf8"></property>
<property name="username" value="root"></property>
<property name="password" value="123456"></property>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="cn/bobo/BolgMapper/BolgMapper.xml"/>
</mappers>
</configuration>
4.创建实体类和接口
实体类:自己实现get set方法:
package cn.bobo.BolgDao;
import java.util.Date;
public class Bolg {
private String id;
private String title;
private String author;
private Date createTime;
private int views
}
接口:
public interface BolgMapper {
int addBolg(Bolg bolg);
5.实现xml文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.bobo.BolgMapper.BolgMapper">
<insert id="addBolg" parameterType="cn.bobo.BolgDao.Bolg">
insert into blog (id, title, author, create_time, views)
values (#{id},#{title},#{author},#{createTime},#{views});
</insert>
</mapper>
6.创建测试类,进行测试
package cn.bobo;
import cn.bobo.BolgDao.Bolg;
import cn.bobo.BolgMapper.BolgMapper;
import cn.bobo.Tools.IDutil;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
public class test {
public InputStream in;
public SqlSession sqlSession;
public BolgMapper bolgMapper;
public SqlSessionFactory factory;
@Before
public void init() throws IOException {
//读取配置文件,生成字节输入流
in = Resources.getResourceAsStream("mybatis.xml");
//获取sqlSessionFactory
factory = new SqlSessionFactoryBuilder().build(in);
//获取sqlSession对象
sqlSession = factory.openSession();
//获取dao的代理对象
bolgMapper = sqlSession.getMapper(BolgMapper.class);
}
@After
public void destroy() throws IOException {
//提交事务
sqlSession.commit();
sqlSession.close();
in.close();
}
@Test
public void addInitBlog(){
Bolg bolg = new Bolg();
bolg.setId(IDutil.genld());
bolg.setTitle("wuhu");
bolg.setAuthor("xiaobo");
bolg.setCreateTime(new Date());
bolg.setViews(9999);
bolgMapper.addBolg(bolg);
bolg.setId(IDutil.genld());
bolg.setTitle("Java如此简单");
bolgMapper.addBolg(bolg);
bolg.setId(IDutil.genld());
bolg.setTitle("Spring如此简单");
bolgMapper.addBolg(bolg);
bolg.setId(IDutil.genld());
bolg.setTitle("hahha");
bolgMapper.addBolg(bolg);
}
@Test
public void testQueryBolgif(){
HashMap<String,String> map = new HashMap<String, String>();
map.put("title","wuhu");
map.put("author","xiaobo");
List<Bolg> bolgs = bolgMapper.queryBolgIf(map);
System.out.println(bolgs);
}
@Test
public void testUpdateBolg(){
HashMap<String,String>
}
}
3.if标签
编写接口:
List queryBlogIf(Map map);
编写SQL语句:
<select id="queryBlogIf" parameterType="map" resultType="blog">
select * from blog where
<if test="title != null">
title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</select>
测试:
@Test
public void testQueryBlogIf(){
SqlSession session = MybatisUtils.getSession();
BlogMapper mapper = session.getMapper(BlogMapper.class);
HashMap<String, String> map = new HashMap<String, String>();
map.put("title","Mybatis如此简单");
map.put("author","狂神说");
List<Blog> blogs = mapper.queryBlogIf(map);
System.out.println(blogs);
session.close();
}
结果:
这里能看到如果title为空 则会执行第二个if语句,开头是and 所以会显示报错,所以我们用到where标签
4.where标签
修改上一条的SQL语句即可:
<select id="queryBolgIf" parameterType="map" resultType="cn.bobo.BolgDao.Bolg">
select * from blog
<where>
<if test="title != null">
title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</where>
</select>
5.Set标签
在至少有一个子元素返回了SQL语句时,才会向SQL语句中添加SET,并且如果SET之后是以,开头的话,会自动将其删掉
常用在修改的标签中
SQL语句:
<update id="updateBolg" parameterType="map">
update blog
<set>
<if test="title != null">
title = #{title},
</if>
<if test="author != null">
author = #{author}
</if>
</set>
where id = #{id};
</update>
测试类:
@Test
public void testUpdateBlog(){
HashMap<String, String> map = new HashMap<String, String>();
map.put("title","在山里");
map.put("author","雪豹");
map.put("id","3b972c22cbd74c8dbfaaf35b4fa732fb");
blogMapper.updateBolg(map);
}
6.Choose标签
有时候用不到所有的查询条件,只想选择其中的一个,查询条件有一个满足即可,使用choose标签可以满足
接口:
List<Blog> queryBlogChoose(Map map);
SQL语句:
<select id="queryBlogChoose" parameterType="map" resultType="cn.bobo.BolgDao.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>
测试类:
@Test
public void testQueryBlogChoose(){
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("title","Java如此简单");
map.put("author","狂神说");
map.put("views",9999);
List<Bolg> bolgs = mapper.queryBolgChoose(map);
System.out.println(blogs);
}
7.SQL片段
有时候可以通过将部分代码抽出来作为公用,使用时候可以直接调用
SQL片段;
<sql id="if-title-author">
<if test="title != null">
title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</sql>
引用SQL片段:
<select id="queryBolgIf" parameterType="map" resultType="cn.bobo.BolgDao.Bolg">
select * from blog
<where>
<!-- 引用 sql 片段,如果refid 指定的不在本文件中,那么需要在前面加上 namespace -->
<include refid="if-title-author"></include>
<!-- 在这里还可以引用其他的 sql 片段 -->
</where>
</select>
注意:在sql片段中不要包括where
8.Foreach
接口:
List<Blog> queryBlogForeach(Map map);
编写SQL语句:
<select id="queryBlogForeach" parameterType="map" resultType="cn.bobo.BolgDao.Bolg">
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>
测试类:
@Test
public void testQueryBlogForeach(){
SqlSession session = MybatisUtils.getSession();
BlogMapper mapper = session.getMapper(BlogMapper.class);
HashMap map = new HashMap();
List<Integer> ids = new ArrayList<Integer>();
ids.add(1);
ids.add(2);
ids.add(3);
map.put("ids",ids);
List<Blog> blogs = mapper.queryBlogForeach(map);
System.out.println(blogs)
}