1. 结果映射(resultMap)
association – 一个复杂类型的 关联;许多结果将包装成这种类型
嵌套结果映射 – 关联可以是 resultMap 元素,或是对其它结果映射的引用。多对1,关联。
collection – 一个复杂类型的 集合
嵌套结果映射 – 和上面一样。 1对多。老师管理一个集合的学生。
SQL
- 多对1
CREATE TABLE `teacher` (
`id` int(10) NOT NULL,
`name` varchar(30) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
INSERT INTO `mybatis`.`teacher`(`id`, `name`) VALUES (1, '秦老师');
CREATE TABLE `student` (
`id` int(11) NOT NULL,
`name` varchar(30) DEFAULT NULL,
`tid` int(10) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `fktid` (`tid`),
CONSTRAINT `fktid` FOREIGN KEY (`tid`) REFERENCES `teacher` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
INSERT INTO `mybatis`.`student`(`id`, `name`, `tid`) VALUES (1, '小明', 1);
INSERT INTO `mybatis`.`student`(`id`, `name`, `tid`) VALUES (2, '小红', 1);
实体类
- com.hou.pojo下:
@Data
public class Student {
private int id;
private String name;
//学生需要关联一个老师
private Teacher teacher;
}
@Data
public class Teacher {
private int id;
private String name;
}
配置
接口: com.hou.dao
public interface StudentMapper {
}
public interface TeacherMapper {
@Select("select * from teacher where id =#{tid}")
Teacher getTeacher(@Param("tid") int id);
}
resources下:com.hou.dao.TeacherMapper.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.hou.dao.TeacherMapper">
</mapper>
<!--绑定接口-->
<mappers>
<mapper class="com.hou.dao.TeacherMapper"></mapper>
<mapper class="com.hou.dao.StudentMapper"></mapper>
</mappers>
2. 多对1
1:按查询嵌套,子查询
List<Student> getStudent();
- StudentMapper.xml
<select id="getStudent" resultMap="StudentTeacher">
select * from student;
</select>
<resultMap id="StudentTeacher" type="com.hou.pojo.Student">
<result property="id" column="id"></result>
<result property="name" column="name"></result>
<!--对象使用assiociation-->
<!--集合用collection-->
//当前的实体类的属性。数据库查出来的(不能错)。关联的具体的实体类(可不写)
<association property="teacher" column="tid"
javaType="com.hou.pojo.Teacher"
select="getTeacher"></association>
</resultMap>
<select id="getTeacher" resultType="com.hou.pojo.Teacher">
select * from teacher where id = #{tid}; //只有一个参数,可任意写
</select>
2:按结果嵌套,连表查询
<select id="getStudent2" resultMap="StudentTeacher2">
select s.id sid,s.name sname,t.name tname
from student s,teacher t where s.tid=t.id;
</select>
<resultMap id="StudentTeacher2" type="com.hou.pojo.Student">
<result property="id" column="sid"></result>
<result property="name" column="sname"></result>
<association property="teacher" javaType="com.hou.pojo.Teacher">
<result property="name" column="tname"></result>
</association>
</resultMap>
3. 1对多
@Data
public class Teacher {
private int id;
private String name;
//一个老师拥有多个学生
private List<Student> students;
}
结果嵌套处理
<!--按结果嵌套查询-->
<select id="getTeacher" resultMap="StudentTeacher">
SELECT s.id sid, s.name sname,t.name tname,t.id tid FROM student s, teacher t
WHERE s.tid = t.id AND tid = #{tid}
</select>
<resultMap id="StudentTeacher" type="Teacher">
<result property="id" column="tid"/>
<result property="name" column="tname"/>
<!--复杂的属性,我们需要单独处理 对象:association 集合:collection
javaType=""指定属性的类型!
集合中的泛型信息,我们使用ofType获取
-->
<collection property="students" ofType="Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<result property="tid" column="tid"/>
</collection>
</resultMap>
查询嵌套,子查询
<!--可以给实体类起别名-->
<typeAliases>
<!--<typeAlias type="pojo.User" alias="User"></typeAlias>-->
<package name="pojo"/>
</typeAliases>
<select id="selectById2" resultMap="teacherStudent2">
select *
from teacher
where id = #{tid}
</select>
<resultMap id="teacherStudent2" type="teacher"> //teacher 和 student 配置了扫描
<result property="id" column="id"/> //必须写,默认 id 传递给 下面的 列了。
<collection property="students" javaType="ArrayList" ofType="student" column="id"
select="selectStudentByTeacherId"/>
</resultMap>
<select id="selectStudentByTeacherId" resultType="student">
select *
from student
where tid = #{tid}
</select>
4. 小结
1.关联 - association 【多对一】
2.集合 - collection 【一对多】
3.javaType & ofType
- JavaType用来指定实体类中的类型
- ofType用来指定映射到List或者集合中的pojo类型,泛型中的约束类型
** 注意点:**
- 保证SQL的可读性,尽量保证通俗易懂
- 注意一对多和多对一,属性名和字段的问题
- 如果问题不好排查错误,可以使用日志,建议使用Log4j
面试高频
- Mysql引擎
- InnoDB底层原理
- 索引
- 索引优化
5. 动态SQL
什么是动态SQL:动态SQL就是根据不同的条件生成不同的SQL语句
所谓的动态SQL,本质上还是SQL语句,只是我们可以在SQL层面,去执行一个逻辑代码
动态 SQL 是 MyBatis 的强大特性之一。如果你使用过 JDBC 或其它类似的框架,你应该能理解
根据不同条件拼接 SQL 语句有多痛苦,例如拼接时要确保不能忘记添加必要的空格,还要注意去
掉列表最后一个列名的逗号。利用动态 SQL,可以彻底摆脱这种痛苦。
if
choose (when otherwise)
trim (where set)
foreach
搭建环境
CREATE TABLE `mybatis`.`blog` (
`id` int(10) NOT NULL AUTO_INCREMENT COMMENT '博客id',
`title` varchar(30) NOT NULL COMMENT '博客标题',
`author` varchar(30) NOT NULL COMMENT '博客作者',
`create_time` datetime(0) NOT NULL COMMENT '创建时间',
`views` int(30) NOT NULL COMMENT '浏览量',
PRIMARY KEY (`id`)
)
@Data
public class Blog {
private int id;
private String title;
private String author;
private Date createTime;// 属性名和字段名不一致
private int views;
}
<settings>
//下划线,转 驼峰
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
@SuppressWarnings("all")
public class IDUtiles {
public static String getId(){
return UUID.randomUUID().toString().replaceAll("-","");
}
@Test
public void test(){
System.out.println(getId());
}
}
IF
List<Blog> queryBlogIF(Map map);
Map map = new HashMap();
map.put("title", "first");
List<Blog> list = blogMapper.queryBlogIF(map);
//map可以直接小写。== Map。也可以写全路径
//https://blog.csdn.net/weixin_44827418/article/details/111429783
<select id="queryBlogIF" parameterType="map" resultType="Blog">
select * from mybatis.blog //where 1=1 <if .... 也行
<where>
<include refid="if-title-author"></include>
</where>
</select>
<sql id="if-title-author">
<if test="title != null">
title = #{title}
</if>
<if test="author != null">
and author = #{author} //如果:第一个条件 不成立,因为 前面有 where,会去掉 第二个条件的and
</if>
</sql>
choose
choose (when otherwise 只选其一分支)
<select id="queryBlogchoose" parameterType="map" resultType="Blog">
select * from mybatis.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>
set where trim
Integer updateBlog(Map map);
<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="WHERE" prefixOverrides="AND |OR ">
... 前缀是 where ,如果 第一个是 and 或 or,就清理
</trim>
// 和 <set> 标签 不能同时使用,相当于一个set了。
<trim prefix="SET" suffixOverrides=",">
... 前缀是 set,如果 后缀是 逗号 就清理。如上 更新的:如果 第二个 没有 值,就去掉 第一个的 逗号。
</trim>
foreach
使用map拼接
List<Blog> queryBlogForeach(Map map);
Map map = new HashMap();
ArrayList<Integer> ids = new ArrayList<Integer>();
ids.add(1);
ids.add(3);
map.put("ids",ids);
List<Blog> list = blogMapper.queryBlogForeach(map);
<!--ids是传的,#{id}是遍历的-->
<select id="queryBlogForeach" parameterType="map" resultType="Blog">
select * from mybatis.blog
<where>
<foreach collection="ids" item="id" open="and (" //and 不用拼接。这里拼接了 自动去掉
close=")" separator="or">
id=#{id}
</foreach>
</where>
</select>
//自动去掉了 and
select * from blog WHERE ( id=1 or id=3 )
//加了条件后,会自动 加上 and
select * from blog WHERE 1=1 and ( id=? or id=? )
where id=1 or id=2 or id=3
使用List拼接
List<Blog> queryBlogForeach2(@Param("list") List list); //Param 可不写
select * from mybatis.blog WHERE id in ( ? , ? )
<select id="queryBlogForeach2" resultType="Blog" parameterType="List"> //parameterType 可不写
select * from mybatis.blog
<where>
<foreach collection="list" item="id" open="id in ("
close=")" separator=",">
#{id}
</foreach>
</where>
</select>
官方的文档
<select id="selectPostIn" resultType="domain.blog.Post">
SELECT *
FROM POST P
<where> //或者把 ID in 写在这
<foreach item="item" index="index" collection="list"
open="ID in (" separator="," close=")" nullable="true">
#{item}
</foreach>
</where>
</select>
6. 缓存
简介
查询 : 连接数据库,耗资源
一次查询的结果,给他暂存一个可以直接取到的地方 --> 内存:缓存
我们再次查询的相同数据的时候,直接走缓存,不走数据库了
1.什么是缓存[Cache]?
-
存在内存中的临时数据
-
将用户经常查询的数据放在缓存(内存)中,用户去查询数据就不用从磁盘上(关系型数据库文件)查询,从缓存中查询,从而提高查询效率,解决了高并发系统的性能问题
2.为什么使用缓存?
- 减少和数据库的交互次数,减少系统开销,提高系统效率
3.什么样的数据可以使用缓存?
- 经常查询并且不经常改变的数据 【可以使用缓存】
MyBatis缓存
- MyBatis包含一个非常强大的查询缓存特性,它可以非常方便的定制和配置缓存,缓存可以极大的提高查询效率。
- MyBatis系统中默认定义了两级缓存:一级缓存和二级缓存
- 默认情况下,只有一级缓存开启(SqlSession级别的缓存,closed后 无效,也称为本地缓存)
- 二级缓存需要手动开启和配置,他是基于namespace级别的缓存。(一个接口,一个namespace)
- 为了提高可扩展性,MyBatis定义了缓存接口Cache。我们可以通过实现Cache接口来定义二级缓存。
二级缓存 官网
Mapper上 加标签,默认不写参数
<cache
eviction="FIFO"
flushInterval="60000"
size="512"
readOnly="true"/>
这个更高级的配置创建了一个 FIFO 缓存,每隔 60 秒刷新,最多可以存储结果对象或列表的 512 个引用,而且返回的对象被认为是只读的,因此对它们进行修改可能会在不同线程中的调用者产生冲突。
可用的清除策略有:
LRU
– 最近最少使用:移除最长时间不被使用的对象。FIFO
– 先进先出:按对象进入缓存的顺序来移除它们。SOFT
– 软引用:基于垃圾回收器状态和软引用规则移除对象。WEAK
– 弱引用:更积极地基于垃圾收集器状态和弱引用规则移除对象。
默认的清除策略是 LRU。
public interface Cache {
String getId();
void putObject(Object var1, Object var2);
Object getObject(Object var1);
Object removeObject(Object var1);
void clear();
int getSize();
default ReadWriteLock getReadWriteLock() {
return null;
}
}
LruCache implements Cache
ScheduledCache implements Cache
LoggingCache implements Cache
SynchronizedCache implements Cache
AbstractEhcacheCache implements Cache
FifoCache implements Cache
一级缓存
- 一级缓存也叫本地缓存:SqlSession
- 与数据库同一次会话期间查询到的数据会放在本地缓存中
- 以后如果需要获取相同的数据,直接从缓存中拿,没必要再去查询数据库
测试步骤:
1.开启日志
2.测试在一个Session中查询两次记录
@Test
public void test1() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.getUserById(1);
System.out.println(user);
System.out.println("=====================================");
User user2 = mapper.getUserById(1);
System.out.println(user2 == user); //为 true,连 地址都是一样的
}
- mybatisPlus 默认 每次查询都会关 sqlSession,开了事务后,就不关了。
@Autowired
private SqlSession sqlSession;
@Transactional
@Test
void test2() {
TeacherMapper teacherMapper = sqlSession.getMapper(TeacherMapper.class);
Teacher teacher = teacherMapper.getTeacher(1);
Teacher teacher2 = teacherMapper.getTeacher(1);
System.out.println(teacher == teacher2);
}
缓存失效的情况:
1.查询不同的东西
2.增删改操作(哪怕不是这条数据),可能会改变原来的数据,所以必定会刷新缓存。
3.查询不同的Mapper.xml
4.手动清理缓存
sqlSession.clearCache();
二级缓存
- 二级缓存也叫全局缓存,一级缓存作用域太低了,所以诞生了二级缓存
- 基于namespace级别的缓存,一个名称空间,对应一个二级缓存
- 工作机制
- 一个会话查询一条数据,这个数据就会被放在当前会话的一级缓存中
- 如果会话关闭了,这个会员对应的一级缓存就没了;但是我们想要的是,会话关闭了,一级缓存中的数据被保存到二级缓存中
- 新的会话查询信息,就可以从二级缓存中获取内容
- 不同的mapper查询出的数据会放在自己对应的缓存(map)中
一级缓存开启(SqlSession级别的缓存,也称为本地缓存)
- 二级缓存需要手动开启和配置,他是基于namespace级别的缓存。
- 为了提高可扩展性,MyBatis定义了缓存接口Cache。我们可以通过实现Cache接口来定义二级缓存。
步骤:
1.开启全局缓存
<!--显示的开启全局缓存-->
<settings>
<setting name="cacheEnabled" value="true"/>
</settings>
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
cache-enabled: true
mapper-locations: classpath*:com/example/demomp/mapper/**/xml/*Mapper.xml
2.在Mapper.xml中使用缓存
<!--在当前Mapper.xml中使用二级缓存。myBatisPlus 开启缓存,配置这个后,也会生效-->
<cache
eviction="FIFO"
flushInterval="60000"
size="512"
readOnly="true"/>
<select id="queryUserByid" resultType="User" useCache="false"> //某一个sql配置缓存
<update id="updateUser" parameterType="User" flushCache="false">//更新的时候,不刷新缓存
3.测试
1.问题:我们需要将实体类序列化,否则就会报错。 Not Serializable Exception
- mybatisPlus 加lombok注解@Data,无需 implements Serializable
public class User implements Serializable { }
@Test
public void addBlog(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
SqlSession sqlSession1 = MybatisUtils.getSqlSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
User user = userMapper.queryUserByid(1);
System.out.println(user);
sqlSession.close();//回话关闭,放入二级缓存。如果是不同的mapper,那缓存没用。
UserMapper userMapper1 = sqlSession1.getMapper(UserMapper.class);
User user1 = userMapper1.queryUserByid(1);
System.out.println(user1);
System.out.println(user==user1); //true。讲课中 运行,出现了一次FALSE(每查数据库)。
sqlSession1.close();
}
小结:
- 只要开启了二级缓存,在同一个Mapper下就有效
- 所有的数据都会放在一级缓存中
- 只有当前会话提交,或者关闭的时候,才会提交到二级缓存中
缓存原理
- 先看 二级缓存中 有没有
- 在看 一级缓存中 有没有
- 查询 数据库
自定义缓存-ehcache
Ehcache是一种广泛使用的开源Java分布式缓存。主要面向通用缓存
1.导包
<dependency>
<groupId>org.mybatis.caches</groupId>
<artifactId>mybatis-ehcache</artifactId>
<version>1.2.1</version>
</dependency>
2.在mapper中指定使用我们的ehcache缓存实现
<cache type="org.mybatis.caches.ehcache.EhcacheCache"/> //自己实现Cache接口,也能配置到这
Resource 下 增加 ehcache.xml
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
updateCheck="false">
<!--
diskStore:为缓存路径,ehcache分为内存和磁盘两级,此属性定义磁盘的缓存位置。参数解释如下:
user.home – 用户主目录
user.dir – 用户当前工作目录
java.io.tmpdir – 默认临时文件路径
-->
<diskStore path="java.io.tmpdir/Tmp_EhCache"/>
<!--
defaultCache:默认缓存策略,当ehcache找不到定义的缓存时,则使用这个缓存策略。只能定义一个。
-->
<!--
name:缓存名称。
maxElementsInMemory:缓存最大数目
maxElementsOnDisk:硬盘最大缓存个数。
eternal:对象是否永久有效,一但设置了,timeout将不起作用。
overflowToDisk:是否保存到磁盘,当系统当机时
timeToIdleSeconds:设置对象在失效前的允许闲置时间(单位:秒)。仅当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。
timeToLiveSeconds:设置对象在失效前允许存活时间(单位:秒)。最大时间介于创建时间和失效时间之间。仅当eternal=false对象不是永久有效时使用,默认是0.,也就是对象存活时间无穷大。
diskPersistent:是否缓存虚拟机重启期数据 Whether the disk store persists between restarts of the Virtual Machine. The default value is false.
diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区。
diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒。
memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)。
clearOnFlush:内存数量最大时是否清除。
memoryStoreEvictionPolicy:可选策略有:LRU(最近最少使用,默认策略)、FIFO(先进先出)、LFU(最少访问次数)。
FIFO,first in first out,这个是大家最熟的,先进先出。
LFU, Less Frequently Used,就是上面例子中使用的策略,直白一点就是讲一直以来最少被使用的。如上面所讲,缓存的元素有一个hit属性,hit值最小的将会被清出缓存。
LRU,Least Recently Used,最近最少使用的,缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存。
-->
<defaultCache
eternal="false"
maxElementsInMemory="10000"
overflowToDisk="false"
diskPersistent="false"
timeToIdleSeconds="1800"
timeToLiveSeconds="259200"
memoryStoreEvictionPolicy="LRU"/>
<cache
name="cloud_user"
eternal="false"
maxElementsInMemory="5000"
overflowToDisk="false"
diskPersistent="false"
timeToIdleSeconds="1800"
timeToLiveSeconds="1800"
memoryStoreEvictionPolicy="LRU"/>
</ehcache>
cache-ref
回想一下上一节的内容,对某一命名空间的语句,只会使用该命名空间的缓存进行缓存或刷新。 但你可能会想要在多个命名空间中共享相同的缓存配置和实例。要实现这种需求,你可以使用 cache-ref 元素来引用另一个缓存。
<cache-ref namespace="com.someone.application.data.SomeMapper"/>