文章目录
1. 动态SQL
1.1 什么是动态SQL?
什么是动态SQL?
- 动态SQL就是指根据不同的条件生成不同的SQL语句。
平时我们操作一些不同的sql语句,都是直接在代码上更改,很麻烦。通过Mybatis的动态SQL就很方便。
利用动态SQL这一特性可以彻底摆脱这种痛苦。
如果你之前用过 JSTL 或任何基于类 XML 语言的文本处理器,你对动态 SQL 元素可能会感觉似曾相识。在 MyBatis 之前的版本中,需要花时间了解大量的元素。借助功能强大的基于 OGNL 的表达式,MyBatis 3 替换了之前的大部分元素,大大精简了元素种类,现在要学习的元素种类比原来的一半还要少。
要学习的内容也就下面4个标签:
if
choose (when, otherwise)
trim (where, set)
foreach
1.2 准备工作
Blog实体类:
package com.itholmes.pojo;
import lombok.Data;
import java.util.Date;
@Data
public class Blog {
private String id;
private String title;
private String author;
/*
对于这种驼峰命名,对应数据库的内容,我们可以在mybatis的核心配置文件的setting配置,mapUnderscoreToCamelCase为true.
*/
private Date createTime;
private int views;
}
创建一个IDUtils类,来获取UUId的一个字符串。将这个字符串作为Blog的id属性。
package com.itholmes.utils;
import org.junit.jupiter.api.Test;
import java.util.UUID;
public class IDUtils {
public static String getUUId(){
/*
UUID.randomUUID().toString()来生成一个uuid字符串。
注意:UUID是不会重复的!
*/
return UUID.randomUUID().toString().replaceAll("-","");
}
//测试uuid的效果。
@Test
public void test(){
String uuId = IDUtils.getUUId();
String uuId2 = IDUtils.getUUId();
String uuId3 = IDUtils.getUUId();
System.out.println(uuId);
System.out.println(uuId2);
System.out.println(uuId3);
}
}
1.3 动态SQL之if语句
<select id="findActiveBlogWithTitleLike"
resultType="Blog">
SELECT * FROM BLOG
WHERE state = ‘ACTIVE’
<if test="title != null">
AND title like #{title}
</if>
</select>
结构就是:if标签加一个test属性,test属性中是字段名的一些限制语句啥的。
BlogMapper.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">
<mapper namespace="com.itholmes.dao.BlogMapper">
<select id="queryBlogIF" parameterType="map" resultType="com.itholmes.pojo.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>
</mapper>
BlogMapper接口类:
package com.itholmes.dao;
import com.itholmes.pojo.Blog;
import java.util.List;
import java.util.Map;
public interface BlogMapper {
//查询博客
List<Blog> queryBlogIF(Map map);
}
测试类:
import com.itholmes.dao.BlogMapper;
import com.itholmes.pojo.Blog;
import com.itholmes.utils.IDUtils;
import com.itholmes.utils.MybatisSqlSession;
import org.apache.ibatis.session.SqlSession;
import org.junit.jupiter.api.Test;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
public class test {
@Test
public void test2(){
SqlSession sqlSession = MybatisSqlSession.getMybatisSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap map = new HashMap();
map.put("title","数据结构");
map.put("author","张三");
List<Blog> list = mapper.queryBlogIF(map);
for (Blog blog : list) {
System.out.println(blog);
}
sqlSession.close();
}
}
1.4 动态SQL的trim(where , set)
where作用很关键,我们在执行一些动态SQL的语句时,可能会出现sql语句拼接的错误。如下:
作用:where 元素只会在子元素返回任何内容的情况下才插入 “WHERE” 子句。而且,若子句的开头为 “AND” 或 “OR”,where 元素也会将它们去除。
set的作用:set元素会动态前置SET关键字(update set语句的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>
trim元素有四个属性:
- prefix属性:给语句开头添加prefix的值。
- prefixOverrides属性:语句开头如果匹配到prefixOverrides属性值,就移除。之后将prefix的属性值放到sql前面。
- suffix属性:给语句末尾添加suffix的值。
- suffixOverrides属性:语句末尾如果匹配到suffixOverrides属性值,就移除。
trim标签元素就是基于整个sql语句来操作的:
- 将整个标签匹配到的结果,先进行suffixOverrides,prefixOverrides进行匹配移除;在prefix,suffix进行收尾添加。
如下:
<update id="updateBlog" parameterType="map">
update mybatis.blog
<trim prefix="set" suffixOverrides="," suffix="where id = #{id}">
<if test="title != null">
title = #{title},
</if>
<if test="author != null">
author = #{author},
</if>
</trim>
</update>
1.5 动态SQL之 choose(when ,otherwise) 语句
<select id="findActiveBlogLike"
resultType="Blog">
SELECT * FROM BLOG WHERE state = ‘ACTIVE’
<choose>
<when test="title != null">
AND title like #{title}
</when>
<when test="author != null and author.name != null">
AND author_name like #{author.name}
</when>
<otherwise>
AND featured = 1
</otherwise>
</choose>
</select>
choose,when,otherwise。就类似Java代码中的switch,case,default。
BlogMapper.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">
<mapper namespace="com.itholmes.dao.BlogMapper">
<select id="queryBlogChoose" parameterType="map" resultType="com.itholmes.pojo.Blog">
select * from mybatis.blog
<where>
<choose>
<when test="title != null">
-- 这里不需要and,因为第一个元素前面是where。
title = #{title};
</when>
<when test="author != null">
and author = #{author}
</when>
<otherwise>
and views = #{views}
</otherwise>
</choose>
</where>
</select>
</mapper>
BlogMapper接口类:
package com.itholmes.dao;
import com.itholmes.pojo.Blog;
import java.util.List;
import java.util.Map;
public interface BlogMapper {
//choose测试
List<Blog> queryBlogChoose(Map map);
}
测试类:
public void test3(){
SqlSession sqlSession = MybatisSqlSession.getMybatisSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap map = new HashMap();
// map.put("title","数据结构");
// map.put("author","张三");
map.put("views",999);
List<Blog> list = mapper.queryBlogChoose(map);
for (Blog blog : list) {
System.out.println(blog);
}
sqlSession.close();
}
1.6 动态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="com.itholmes.pojo.Blog">
select * from mybatis.blog
<where>
<include refid="if-title-author"></include>
</where>
</select>
sql片段的注意事项:
- 最好基于单表来定义SQL片段。
- sql标签中,不要存在where标签。
1.7 动态SQL之 foreach 语句
foreach元素的作用:对集合进行遍历(尤其是在构建 IN 条件语句的时候)。
foreach很简单,对应他们的属性名就能理解如下:
<!--
使用foreach进行查询。
演示下面的语句:
select * from mybatis.blog where 1=1 and (id = 1 or id = 2 or id = 3);
这里接受的一个map,这个map中可以存一个集合。
-->
<select id="queryBlogForeach" parameterType="map" resultType="com.itholmes.pojo.Blog">
select * from mybatis.blog
<where>
<foreach collection="ids" item="id" open="and (" close=")" separator="or">
id = #{id}
</foreach>
</where>
</select>
2. 什么是缓存(Cache)? 缓存在架构中的作用?
我们查询数据时,首先需要连接数据库,拿到数据传到后台。这样我们每一次的查询结果,可以将它暂存到一个可以直接获取到的地方!那就是内存。而这种临时数据就是缓存了。
什么是缓存(Cache)?
- 存在内存中的临时数据。
- 将用户经常查询的数据放在缓存(内存)中,用户去查询数据就不用从磁盘上(关系型数据库数据文件)查询,直接从缓存中查询,从而提高查询效率,解决
高并发系统的性能问题
。
对于架构方面的了解:
3. Mybatis缓存
4. Mybatis 一级缓存
4.1 准备工作 和 一级缓存的案例
User实体类:
package com.itholmes.pojo;
import lombok.Data;
@Data
@AllArgsConstructor
public class User {
private int id;
private String name;
private String pwd;
}
UserMapper接口类:
package com.itholmes.dao;
import com.itholmes.pojo.User;
import org.apache.ibatis.annotations.Param;
public interface UserMapper {
//查询指定id的用户给
User queryUsers(@Param("id") int a);
}
UserMapper.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">
<mapper namespace="com.itholmes.dao.UserMapper">
<select id="queryUsers" parameterType="int" resultType="User">
select * from user where id = #{id};
</select>
</mapper>
测试类:
import com.itholmes.dao.UserMapper;
import com.itholmes.pojo.User;
import com.itholmes.utils.MybatisSqlSession;
import org.apache.ibatis.session.SqlSession;
import org.junit.jupiter.api.Test;
public class test {
@Test
public void test(){
SqlSession sqlSession = MybatisSqlSession.getMybatisSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user1 = mapper.queryUsers(1);
System.out.println(user1);
System.out.println("===================");
User user2 = mapper.queryUsers(1);
System.out.println(user2);
System.out.println("user1 和 user2 是否相等:" + (user1==user2));
sqlSession.close();
}
}
我们从执行结果得出,两次相同的查询,仅仅调用了一次sql,并且得到的对象相同(对象地址相同),这第二次查询就用到了缓存的效果。这里mybatis默认是开启一级缓存的。
4.2 一级缓存 失效(清理)的情况
缓存必须要有失效的情况(失效了,就要清理缓存),如果数据库的数据发生了变化,而缓存没有,这样拿到的数据就有大问题了!!
缓存失效的情况:
- 1.插叙不同的数据。
- 2.增删改操作,可能会改变原来的数据,所以必定会刷新缓存!!例如:
import com.itholmes.dao.UserMapper;
import com.itholmes.pojo.User;
import com.itholmes.utils.MybatisSqlSession;
import org.apache.ibatis.session.SqlSession;
import org.junit.jupiter.api.Test;
public class test {
@Test
public void test(){
SqlSession sqlSession = MybatisSqlSession.getMybatisSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user1 = mapper.queryUsers(1);
System.out.println(user1);
System.out.println("这里我们加入了更新操作,那么原来的缓存就会失效!!!从而重新加载。");
mapper.updateUser(new User(2,"王五","1234"));
System.out.println("===============================================");
User user2 = mapper.queryUsers(1);
System.out.println(user2);
System.out.println("user1 和 user2 是否相等:" + (user1 == user2));
sqlSession.close();
}
}
- 3.查询不同的Mapper.xml文件。
- 4.手动清理缓存,使用sqlSession.clearCache();手动清理。如下:
import com.itholmes.dao.UserMapper;
import com.itholmes.pojo.User;
import com.itholmes.utils.MybatisSqlSession;
import org.apache.ibatis.session.SqlSession;
import org.junit.jupiter.api.Test;
public class test {
@Test
public void test(){
SqlSession sqlSession = MybatisSqlSession.getMybatisSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user1 = mapper.queryUsers(1);
System.out.println(user1);
System.out.println("手动清理缓存");
sqlSession.clearCache();
System.out.println("===============================================");
User user2 = mapper.queryUsers(1);
System.out.println(user2);
System.out.println("user1 和 user2 是否相等:" + (user1 == user2));
sqlSession.close();
}
}
4.3 一级缓存 总结
一级缓存默认是开启的,只在一次SqlSession中有效,也就是拿到连接到关闭连接的这个区间段。
默认情况下,只启用了本地的会话缓存,它仅仅对一个会话中的数据进行缓存。因此,我们还需要启用全局的二级缓存。
5. Mybatis 二级缓存
二级缓存也叫全局缓存,由于一级缓存作用域太低了,所以诞生了二级缓存。
二级缓存是基于namespace级别的缓存,一个命名空间,对应一个二级缓存。
二级缓存的工作机制:
启用二级缓存,就只需要在Mapper.xml文件中,声明一个cache标签就可以了。
使用二级缓存的步骤:
- 第一步开启缓存。去mybatis核心配置文件中的setting配置全局是否开启缓存。
<settings>
<!--这里我们使用标椎日志工厂实现-->
<setting name="logImpl" value="STDOUT_LOGGING"/>
<!--是否开启驼峰命名自动映射-->
<setting name="mapUnderscoreToCamelCase" value="true"/>
<!--全局性地开启或关闭所有映射器配置文件中已配置的任何缓存。-->
<setting name="cacheEnabled" value="true"/>
</settings>
- 2.在要使用二级缓存的Mapper.xml文件中开启二级缓存,并且配置相关属性。
不想加载缓存的语句可以用useCache属性来定义
<!--
启用二级缓存:
eviction定义清除缓存策略。
flushInterval定义缓存刷新时间,这里是每隔60刷新缓存。
size最多有多少缓存数量。
readOnly是否只读。
-->
<cache eviction="FIFO"
flushInterval="60000"
size="512"
readOnly="true"/>
二级缓存的测试:
测试类:
import com.itholmes.dao.UserMapper;
import com.itholmes.pojo.User;
import com.itholmes.utils.MybatisSqlSession;
import org.apache.ibatis.session.SqlSession;
import org.junit.jupiter.api.Test;
public class test {
@Test
public void test(){
SqlSession sqlSession1 = MybatisSqlSession.getMybatisSqlSession();
UserMapper mapper = sqlSession1.getMapper(UserMapper.class);
User user1 = mapper.queryUsers(1);
System.out.println(user1);
sqlSession1.close();
/*
到了这里sqlSession1的一级缓存已经结束了,但是二级缓存将一级缓存中的内容加载到了自己的缓存中。
这样我们进行下一个sqlSession2时,就可以直接在二级缓存中拿到数据了。
* */
SqlSession sqlSession2 = MybatisSqlSession.getMybatisSqlSession();
UserMapper mapper2 = sqlSession2.getMapper(UserMapper.class);
User user2 = mapper2.queryUsers(1);
System.out.println(user2);
sqlSession2.close();
//通过这里验证两个user的地址也都相同。
System.out.println("user1 和 user2 是否相等: " + (user1 == user2));
}
}
一般我们使用二级缓存不需要设置什么属性,使用默认的就可以了。
<cache/>
但是如果使用了上面可能会报错,一个java.io.NotSerializableException实体类没有序列化的错误。这样我们就必须要实现序列化给实体类。
在执行测试,效果也是一样的。
二级缓存注意事项:
- 只要开启了二级缓存,在同一个Mapper.xml文件下就有效(不刷新的情况下)。
- 所有的数据都会先放在一级缓存中。只有当sqlSession会话提交,或者关闭的时候,才会提交到二级缓存中(间接说明了二级缓存是事务级别的)。
6. Mybatis 缓存原理
执行缓存的过程原理:
- 1.先查询二级缓存。
- 2.二级缓存没有,在查询一级缓存。
- 3.一级缓存没有,就查询数据库。
7. 自定义缓存
7.1 自定义缓存
实现第三方缓存或者自己缓存方案来创建适配器,来完全覆盖缓存行为。
7.2 Ehcache缓存(了解)
Ehcache是一种广泛使用的开源Java分布式缓存。主要面向通用缓存。
EhCache是Hibernate的二级缓存技术之一。现在,很少人在使用了。
首先,导包,ehcache有很多版本,我们要导入mybatis的ehcache。
之后在我们要是使用该缓存的mapper.xml文件中配置cache元素的type属性指定为ehcache,来覆盖之前的二级缓存。
<!--使用Ehcache缓存。-->
<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>
配置一个ehcache.xml来配置ehcache的一些配置信息等。
运行结果也相同,只不过换了一个二级缓存而已。
往后我们都使用redis数据库来做缓存,这个层面的缓存知道就好。
8. 补充
8.1 orm
ORM(对象关系映射):orm能将数据从数据库中取出来,映射到实体类中。
半自动和全自动: 半自动就是XML 或者注解里通过手动或插件生成 SQL。全自动就是什么不需要配置,自动生成sql。
为什么有的用 ’ / '来标识路径:
resources类专门用来处理配置文件的。
8.2 Mybatis应用动态代理
为什么Mybats通过一个接口和配置文件就能操作数据库呢?
- 因为底层用了反射和动态代理,代理出了一个实现类(代理类)。
8.3 ${} 和 #{} 什么区别?
8.4 预编译语句(PreparedStatement)
在mybatis-config.xml中设置好,logimp ,通过控制台打印出相关日志:
预编译语句(PreparedStatement)
- 预编译语句就是为了防止sql注入的!
通过这些箭头我们可以知道那可是传入数据库的内容,哪些是从数据库得到的内容:
8.5 当传入多个参数时,默认是arg0 ,param1往后的索引参数
8.6 Mybatis是不支持重载的
接口是可以重载的,但是Mybatis是不可以重载的。
一旦重载就乱套了!
8.7 resultMap的id标签
9. 数据库的一对一,一对多,多对一的理解
一对多,一般在数据库中是在 多的那一方
添加外键,对应一的主键
。也就是多的一方
进行维护。
对于上面的效果,反过来就是多对一的效果。但是在多对一中,肯定是表中的每一个元素是一对一的效果。
举个例子,有两个表员工表和部门表:
- 在员工表中看,是多个员工对应一个部门,这是多对一。
- 在单个员工来看,是自身一个员工对应一个部门,这是一对一。
- 在部门表来看,是一个部门对应了多个员工,这是一对多。
在Mybatis中,resultMap使用association和collection来操作:
- association解决一对一,多对一。
- collection解决一对多。
要注意的是一旦写了association和collection所有的对应实体类的属性必须全部配置,不然为空!
10. javatype和oftype
javatype是指定类型的。
oftype是指定泛型类型的。
它们两个都属于association和collection标签的属性。
11. 动态SQL的原理
动态SQL的本质就是修改sql语句字符串。
通过where,set,if等等标签,生成的sql字符串,生成的过程中,会对这个字符串进行一个写修改整理。
最终,将最终没有错误的sql语句发给数据库执行。
预编译语句的话,还要发送参数:
像这些where,set标签都是基于trm标签实现的!
- 例如:写一个自定义where标签。
<trim prefix="WHERE" prefixOverrides="AND |OR ">
...
</trim>