手把手带你搞懂 Mybatis的多对一、一对多、动态SQL和缓存

x33g5p2x  于2021-12-22 转载在 其他  
字(11.4k)|赞(0)|评价(0)|浏览(430)

📒博客首页:崇尚学技术的科班人
🏇小肖来了
🍣今天给大家带来的文章是《手把手带你搞懂 Mybatis的多对一、一对多、动态SQL和缓存》🍣
🍣Mybatis是我们常用的框架之一,它的重要性不言而喻。🍣
🍣希望各位小伙伴们能够耐心的读完这篇文章🍣
🙏博主也在学习阶段,如若发现问题,请告知,非常感谢🙏
💗同时也非常感谢各位小伙伴们的支持💗

1、多对一处理

多对一:

  • 多个学生,对应一个老师
  • 对于学生这边而言,关联… 多个学生,关联一个老师【多对一】
  • 对于老师这边而言,集合,一个老师有很多学生【一对多】

回顾Mysql多对一方式

  • 子查询
  • 联表查询

1.1、SQL 创建数据库

  1. CREATE TABLE `teacher` (
  2. `id` INT(10) NOT NULL,
  3. `name` VARCHAR(30) DEFAULT NULL,
  4. PRIMARY KEY (`id`)
  5. ) ENGINE=INNODB DEFAULT CHARSET=utf8
  6. INSERT INTO teacher(`id`, `name`) VALUES (1, '秦老师');
  7. CREATE TABLE `student` (
  8. `id` INT(10) NOT NULL,
  9. `name` VARCHAR(30) DEFAULT NULL,
  10. `tid` INT(10) DEFAULT NULL,
  11. PRIMARY KEY (`id`),
  12. KEY `fktid` (`tid`),
  13. CONSTRAINT `fktid` FOREIGN KEY (`tid`) REFERENCES `teacher` (`id`)
  14. ) ENGINE=INNODB DEFAULT CHARSET=utf8
  15. INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('1', '小明', '1');
  16. INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('2', '小红', '1');
  17. INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('3', '小张', '1');
  18. INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('4', '小李', '1');
  19. INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('5', '小王', '1');​

1.2、环境搭建

  1. 导入lombok
  2. 新建实体类Teacher,Student
  3. 建立Mapper接口
  4. 建立Mapper.xml文件
  5. 在核心配置文件中绑定注册我们的Mapper接口或者文件!【方式很多,随心选】
  6. 测试查询是否成功

1.3、通过结果进行查询

  1. <!-- 通过结果进行查询 -->
  2. <select id="getStudent" resultMap="StudentTeacher">
  3. select s.id as sid, s.name as sname,t.name as tname from student s, teacher t where s.tid=t.id
  4. </select>
  5. <resultMap id="StudentTeacher" type="Student">
  6. <result property="id" column="sid"></result>
  7. <result property="name" column="sname"/>
  8. <association property="teacher" javaType="Teacher">
  9. <result property="name" column="tname"/>
  10. </association>
  11. </resultMap>

1.4、按照查询嵌套

  1. <!-- 按照查询嵌套-->
  2. <select id="getStudent" resultMap="StudentTeacher">
  3. select * from mybatis.student
  4. </select>
  5. <resultMap id="StudentTeacher" type="student">
  6. <result property="id" column="id" />
  7. <result property="name" column="name" />
  8. <!-- 复杂属性: 对象:association 集合:collection -->
  9. <association property="teacher" column="tid" javaType="Teacher" select="getTeacher"></association>
  10. <!-- 注意这里是select 表示 子查询-->
  11. </resultMap>
  12. <select id="getTeacher" resultType="Teacher">
  13. select * from mybatis.teacher where id=#{id}
  14. </select>

2、一对多处理

比如:一个老师拥有多个学生

对于老师而言,一个老师拥有多个学生的关系

2.1、环境搭建

和刚才一样

编写相应的实体类

  1. @Data
  2. public class Student {
  3. private int id;
  4. private String name;
  5. private int tid;
  6. }
  1. @Data
  2. public class Teacher {
  3. private int id;
  4. private String name;
  5. //一个老师 拥有多个学生
  6. private List<Student> students;
  7. }

2.2、按照结果嵌套处理

  1. <!-- 按照结果查询 -->
  2. <select id="getTeacher" resultMap="TeacherStudent">
  3. select s.id sid,s.name sname,t.id tid, t.name tname
  4. from student s , teacher t
  5. where s.tid=t.id and t.id=#{tid}
  6. </select>
  7. <!-- 其实就是对sql语句的所获取的字段的映射 -->
  8. <resultMap id="TeacherStudent" type="Teacher">
  9. <result property="id" column="tid"/>
  10. <result property="name" column="tname"/>
  11. <!-- List 的类型获取 ofType="Studnet" javaType = "" 指定属性的类型! 集合中的泛型信息,我们使用ofType获取 -->
  12. <collection property="students" ofType="Student">
  13. <result property="id" column="sid"/>
  14. <result property="name" column="sname"/>
  15. </collection>
  16. </resultMap>

2.3、按照查询嵌套处理

  1. <!--按照查询嵌套处理-->
  2. <select id="getTeacher" resultMap="TeacherStudent">
  3. select * from teacher where id = #{tid}
  4. </select>
  5. <resultMap id="TeacherStudent" type="Teacher">
  6. <collection property="students" javaType="List" ofType="Student" select="getStudents" column="id" />
  7. <!-----这里的id就是上面的sql语句和下面这个sql语句的关联点(以上面的为准)------->
  8. </resultMap>
  9. <select id="getStudents" resultType="student">
  10. select * from mybatis.student where tid=#{id}
  11. </select>

2.4、小结

  1. 关联 - association 【多对一】

  2. 集合 - collection【一对多】

  3. JavaType & ofType

  4. javaType 用来指定实体类中属性的类型

  5. ofType 用来指定映射到List或者集合中的pojo类型,泛型中的约束类型

注意点:

  • 保证SQL的可读性,尽量保证通俗易懂
  • 注意一对多和多对一中,属性名和字段的问题
  • 如果问题不好排查错误,可以使用日志,建议使用Log4j

慢SQL 1s 1000s

面试高频

  • Mysql引擎
  • InnoDB底层原理
  • 索引
  • 索引优化

3、动态SQL

什么是动态SQL:是指根据不同的条件生成不同的SQL语句

可以彻底摆脱这种痛苦。

  1. 如果你之前用过 JSTL 或任何基于类 XML 语言的文本处理器,你对动态 SQL 元素可能会感觉似曾相识。在
  2. MyBatis 之前的版本中,需要花时间了解大量的元素。借助功能强大的基于 OGNL 的表达式,MyBatis 3
  3. 换了之前的大部分元素,大大精简了元素种类,现在要学习的元素种类比原来的一半还要少。
  4. if
  5. choose (when, otherwise)
  6. trim (where, set)
  7. foreach

3.1、搭建环境

创建一个基础过程

  1. 导包
  2. 编写配置文件
  3. 编写实体类
  1. @Data
  2. public class Blog {
  3. private String id;
  4. private String title;
  5. private String author;
  6. private Date createTime;
  7. private int views;
  8. }
  1. 编写实体类对应的Mapper接口和Mapper.xml文件

3.2、IF

  1. <select id="queryBlogIf" parameterType="map" resultType="blog">
  2. select * from mybatis.blog where 1=1
  3. <if test="title != null">
  4. and title=#{title}
  5. </if>
  6. <if test="author != null">
  7. and author=#{author}
  8. </if>
  9. </select>

3.3、choose (when, otherwise)

MyBatis 提供了 choose 元素,它有点像 Java 中的 switch 语句。

  1. <select id="queryBlogChoose" parameterType="map" resultType="blog">
  2. select * from mybatis.blog
  3. <where>
  4. <choose>
  5. <when test="title != null">
  6. title=#{title}
  7. </when>
  8. <when test="author != null">
  9. and author=#{author}
  10. </when>
  11. <otherwise>
  12. and views=#{views}
  13. </otherwise>
  14. </choose>
  15. </where>
  16. </select>

3.4、trim (where, set)

< where >: where 元素只会在子元素返回任何内容的情况下才插入 “WHERE” 子句。而且,若子句的开头为 “AND” 或 “OR”,where 元素也会将它们去除

  1. <select id="queryBlogIf" parameterType="map" resultType="blog">
  2. select * from mybatis.blog
  3. <where>
  4. <if test="title != null">
  5. title=#{title}
  6. </if>
  7. <if test="author != null">
  8. and author=#{author}
  9. </if>
  10. </where>
  11. </select>

< set >: set 元素会动态地在行首插入 SET 关键字,并会删掉额外的逗号(这些逗号是在使用条件语句给列赋值时引入的)。

  1. <update id="updateBlog" parameterType="map" >
  2. update mybatis.blog
  3. <set>
  4. <if test="title != null">
  5. title=#{title},
  6. </if>
  7. <if test="author != null">
  8. author=#{author}
  9. </if>
  10. </set>
  11. where id=#{id}
  12. </update>

< trim > :他这只是描述,但是if语句的书写还是和where 、set中的一样

  1. <update id="updateBlog" parameterType="map" >
  2. update mybatis.blog
  3. <trim prefix="set" suffixOverrides=",">
  4. <if test="title != null">
  5. title=#{title},
  6. </if>
  7. <if test="author != null">
  8. author=#{author}
  9. </if>
  10. </trim>
  11. where id=#{id}
  12. </update>

所谓的动态SQL,本质还是SQL语句,只是我们可以在SQL层面,去执行一个逻辑代码

3.5、SQL片段

有的时候,我们会将一些公共部分抽取出来,方便复用。

  1. 使用sql将公共部分抽取出来
  1. <sql id="if_title_author">
  2. <if test="title != null">
  3. title=#{title}
  4. </if>
  5. <if test="author != null">
  6. and author=#{author}
  7. </if>
  8. </sql>
  • 使用include标签将在所需要引用的地方进行引用
  1. <select id="queryBlogIf" parameterType="map" resultType="blog">
  2. select * from mybatis.blog
  3. <where>
  4. <include refid="if_title_author"></include>
  5. </where>
  6. </select>

注意事项:

  • 最好基于单表来定义SQL片段
  • 不要存在where标签

3.6、Foreach

  1. select * from users where 1=1 and (id = 1 or id = 2 or id = 3);

  1. <!-- select * from mybatis.blog where 1=1 and(id = 1 or id = 2 or id = 3) -->
  2. <select id="queryBlogForeach" parameterType="map" resultType="blog">
  3. select * from mybatis.blog
  4. <where>
  5. <foreach collection="ids" item="id" open="and (" close=")" separator="or">
  6. id = #{id}
  7. </foreach>
  8. </where>
  9. </select>

动态SQL就是在拼接语句,我们只要保证SQL的正确性,按照SQL的格式,去排列组合就可以了

建议:

  • 先在Mysql中写出完整的SQL,再去对应的去修改成为我们的动态SQL实现通用即可!

4、缓存

4.1、简介

1、什么是缓存 [ Cache ]?

  • 存在内存中的临时数据。
  • 将用户经常查询的数据放在缓存(内存)中,用户去查询数据就不用从磁盘上(关系型数据库数据文件)查询,从缓存中查询,从而提高查询效率,解决了高并发系统的性能问题。

2、为什么使用缓存?

  • 减少和数据库的交互次数,减少系统开销,提高系统效率。

3、什么样的数据能使用缓存?

  • 经常查询并且不经常改变的数据。

4.2、Mybatis缓存

  • MyBatis包含一个非常强大的查询缓存特性,它可以非常方便地定制和配置缓存。缓存可以极大的提升查询效率。
  • MyBatis系统中默认定义了两级缓存:一级缓存和二级缓存
  • 默认情况下,只有一级缓存开启。(SqlSession级别的缓存,也称为本地缓存)
  • 二级缓存需要手动开启和配置,他是基于namespace级别的缓存。
  • 为了提高扩展性,MyBatis定义了缓存接口Cache。我们可以通过实现Cache接口来自定义二级缓存

4.3、一级缓存

一级缓存也叫本地缓存:

  • 与数据库同一次会话期间查询到的数据会放在本地缓存中。
  • 以后如果需要获取相同的数据,直接从缓存中拿,没必须再去查询数据库;

测试步骤:

  1. 开启日志
  2. 测试在一个SqlSession中查询两次相同记录
  3. 查看日志输出

缓存失效的情况

  1. 查询两次不同的记录
  2. 增删改操作,可能会改变原来的数据,所以必定会刷新缓存

  1. 查询不同的Mapper.xml
  2. 手动清理缓存!

小结:一级缓存默认是开启的,只在一次SqlSession中有效,也就是拿到连接到关闭连接这个区间段

一级缓存就是一个Map

4.4、二级缓存

  • 二级缓存也叫全局缓存,一级缓存作用域太低了,所以诞生了二级缓存

  • 基于namespace级别的缓存,一个名称空间,对应一个二级缓存;

  • 工作机制

  • 一个会话查询一条数据,这个数据就会被放在当前会话的一级缓存中;

  • 如果当前会话关闭了,这个会话对应的一级缓存就没了;但是我们想要的是,会话关闭了,一级缓存中的数据被保存到二级缓存中;

  • 新的会话查询信息,就可以从二级缓存中获取内容;

  • 不同的mapper查出的数据会放在自己对应的缓存(map)中;

使用步骤:

  1. 显示的开启全局缓存
  1. <setting name="cacheEnabled" value="true"/>
  1. 在要使用二级缓存中开启
  1. <cache/>

也可以自定义一些参数

  1. <cache eviction="FIFO" flushInterval="60000" size="512" readOnly="true"/>
  1. 测试:

  2. 问题:我们需要将实体类序列化!否则就会报错!

小结:

  • 只要开启了二级缓存,在同一个Mapper下就有效
  • 所有的数据都会先放在一级缓存中
  • 只有当会话提交,或者关闭的时候,才会提交到二级缓存

4.5、缓存原理

原理说明

  • 我们将和数据库的一次连接看作是一次会话,那么一级缓存就存在于这一次会话中。当会话未提交或者未关闭的时候,我们可以从一级缓存中查询。
  • 如果会话要提交或者关闭了,如果二级缓存开启了。那么一级缓存中的内容会被保存到二级缓存中。从而在一个命名空间中都有效。

4.6、自定义缓存(Ehcache)

Ehcache是一种广泛使用的java分布式缓存,用于通用缓存;

要在应用程序中使用Ehcache,需要引入依赖的jar包

  1. <!-- https://mvnrepository.com/artifact/org.mybatis.caches/mybatis-ehcache -->
  2. <dependency>
  3. <groupId>org.mybatis.caches</groupId>
  4. <artifactId>mybatis-ehcache</artifactId>
  5. <version>1.1.0</version>
  6. </dependency>

在mapper.xml中使用对应的缓存即可

  1. <mapper namespace = “org.acme.FooMapper” >
  2. <cache type = “org.mybatis.caches.ehcache.EhcacheCache” />
  3. </mapper>

编写ehcache.xml文件,如果在加载时未找到/ehcache.xml资源或出现问题,则将使用默认配置。

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd" updateCheck="false">
  3. <!-- diskStore:为缓存路径,ehcache分为内存和磁盘两级,此属性定义磁盘的缓存位置。参数解释如下: user.home – 用户主目录 user.dir – 用户当前工作目录 java.io.tmpdir – 默认临时文件路径 -->
  4. <diskStore path="./tmpdir/Tmp_EhCache"/>
  5. <defaultCache eternal="false" maxElementsInMemory="10000" overflowToDisk="false" diskPersistent="false" timeToIdleSeconds="1800" timeToLiveSeconds="259200" memoryStoreEvictionPolicy="LRU"/>
  6. <cache name="cloud_user" eternal="false" maxElementsInMemory="5000" overflowToDisk="false" diskPersistent="false" timeToIdleSeconds="1800" timeToLiveSeconds="1800" memoryStoreEvictionPolicy="LRU"/>
  7. <!-- defaultCache:默认缓存策略,当ehcache找不到定义的缓存时,则使用这个缓存策略。只能定义一个。 -->
  8. <!-- 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,最近最少使用的,缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存。 -->
  9. </ehcache>

以后使用redis做数据库缓存

相关文章