文章目录
教师和学生的关系图:
1.多表查询
1.1、多对一查询
案例:查询学生表联合老师信息
-
编写pojo类
teacher类:@Data public class Teacher implements Serializable { private int id; private String name; }
Student类:
@Data public class Student implements Serializable { private int id; private String name; private int tid; private Teacher teachers; }
-
编写mapper文件
<mapper namespace="com.g.dao.StudentMapper"> <select id="findall" resultMap="studentmap"> select s.id 学号,s.name 姓名,t.name tname from student s left join teacher t on s.tid = t.id </select> <resultMap id="studentmap" type="student"> <result property="id" column="学号"/> <result property="name" column="姓名"/> <association property="teachers" javaType="teacher"> <result property="name" column="tname"/> </association> </resultMap> </mapper>
-
在核心配置文件中注册mapper文件
<mappers> <mapper resource="com/g/dao/StudentMapper.xml"/> </mappers>
-
测试:
@org.junit.Test public void UserMappertest(){ StudentMapper mapper = sqlSession.getMapper(StudentMapper.class); List<Student> list = mapper.findall(); for (Student student : list) { System.out.println(student); } }
1.2、一对多查询
-
创建pojo类:
Student:@Data public class Student implements Serializable { private int id; private String name; private int tid; }
Teacher:
@Data public class Teacher implements Serializable { private int id; private String name; private List<Student> students; }
-
编写Mapper映射文件:
<mapper namespace="com.g.dao.TeacherMapper"> <select id="findbycol" resultMap="Teachermap" parameterType="map"> select t.name,s.id sid,s.name sname from student s,teacher t where t.id=s.tid and t.name=#{tname} </select> <resultMap id="Teachermap" type="teacher"> <result property="name" column="name"/> <collection property="students" ofType="student"> <result property="id" column="sid"/> <result property="name" column="sname"/> </collection> </resultMap> </mapper>
-
注册Mapper文件:
<mappers> <mapper resource="com/g/dao/TeacherMapper.xml"/> </mappers>
-
测试:
@org.junit.Test public void UserMappertest(){ TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class); HashMap<String, Object> map = new HashMap<String, Object>(); map.put("tname","秦老师"); List<Teacher> list = mapper.findbycol(map); for (Teacher teacher : list) { System.out.println(teacher); } }
2.动态Sql
为了代替在mapper配置文件中编写死的sql语句,出现了动态的sql,可以类比为xml中的标签
2.1、IF
步骤:
-
在dao层编写接口
List<User> findbyif(Map map);
-
在映射文件中编写sql语句(在这里使用了万能的Map的集合)
<select id="findbyif" resultType="User" parameterType="map"> select * from user where true <if test="id!=null"> and id=#{id} </if> <if test="username!=null"> and username=#{username} </if> </select>
-
测试
@Test public void findbyiftest(){ UserMapper mapper = sqlSession.getMapper(UserMapper.class); HashMap map = new HashMap(); map.put("id",1); List<User> list = mapper.findbyif(map); for (User user : list) { System.out.println(user); } }
2.2、Choose(when,otherwise)
<select id="findbychoose" resultType="user" parameterType="map">
select * from user
<where>
<choose>
<when test="id!=null">
and id=#{id}
</when>
<when test="username!=null">
and username=#{username}
</when>
<otherwise>
and password=#{password}
</otherwise>
</choose>
</where>
</select>
测试:
@Test
public void findbychoosetest(){
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
HashMap map = new HashMap();
map.put("id",1);
map.put("password","123");
List<User> list = mapper.findbychoose(map);
for (User user : list) {
System.out.println(user);
}
}
注意
在往map中加值的时候,会走choose中的when的第一个的值,因为,第一个值存在,所以就不会进行到下一个值,并且where标签对sql语句进行了优化,可以在sql语句真的省略and
2.3、TRIM(where,set)
-
where
<select id="findbywhere" resultType="user" parameterType="map"> select * from user <where> and id=#{id} </where> </select>
注意where标签在这里优化了sql语句,对条件进行了甄别,判断是否存在and
-
set
<update id="updatebyset" parameterType="map"> update user <set> <if test="username!=null"> username=#{username}, </if> <if test="password!=null"> password=#{password} </if> </set> where id=#{id} </update>
注意注意这里也对sql进行了优化,优化掉了逗号
2.4、sql片段的抽取和使用
-
抽取,给一个sql标上id
<sql id="findallsql"> select * from user; </sql>
-
使用,使用include这个标签
<select id="findall" resultType="user"> <include refid="findallsql"/> </select>
2.5、Foreach
<select id="findbyfor" parameterType="map" resultType="user">
<include refid="findallsql"/>
<where>
<foreach collection="ids" open="and id in(" close=")" separator="," item="id">
#{id}
</foreach>
</where>
</select>
collection是指传过来的集合,open是指在sql语句中的定义的前括号的位置,close是后括号,separator是指分割符,这里是逗号也可以是or等,item是指在集合中的当前的对象。
@Test
public void findbyfortest(){
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
HashMap map = new HashMap();
ArrayList arrayList = new ArrayList();
for (int num = 1; num <= 3; num++) {
arrayList.add(num);
}
map.put("ids",arrayList);
List<User> list = mapper.findbyfor(map);
for (User user : list) {
System.out.println(user);
}
}
3.缓存(了解)
这里有个提前的知识:
多台数据库之间,读写分离,主从复制
3.1、简介
查询:连接数据库,耗资源!
一次查询的结果,给他暂存在一个可以直接取到的地方!--> 内存 : 缓存
我们再次查询相同数据的时候,直接走缓存,就不用走数据库了
- 什么是缓存 [ Cache ]?
- 存在内存中的临时数据。
- 将用户经常查询的数据放在缓存(内存)中,用户去查询数据就不用从磁盘上(关系型数据库数据文件)查询,从缓存中查询,从而提高查询效率,解决了高并发系统的性能问题。
- 为什么使用缓存?
- 减少和数据库的交互次数,减少系统开销,提高系统效率。
- 什么样的数据能使用缓存?
- 经常查询并且不经常改变的数据。【可以使用缓存】
3.2、Mybatis缓存
- MyBatis包含一个非常强大的查询缓存特性,它可以非常方便地定制和配置缓存。缓存可以极大的提升查询效率。
- MyBatis系统中默认定义了两级缓存:一级缓存和二级缓存
- 默认情况下,只有一级缓存开启。(SqlSession级别的缓存,也称为本地缓存)
- 二级缓存需要手动开启和配置,他是基于namespace级别的缓存。
- 为了提高扩展性,MyBatis定义了缓存接口Cache。我们可以通过实现Cache接口来自定义二级缓存
3.3、一级缓存
- 一级缓存也叫本地缓存: SqlSession
- 与数据库同一次会话期间查询到的数据会放在本地缓存中。
- 以后如果需要获取相同的数据,直接从缓存中拿,没必须再去查询数据库;
测试步骤:
- 开启日志!
- 测试在一个Sesion中查询两次相同记录
- 查看日志输出
缓存失效的情况:
-
查询不同的东西
-
增删改操作,可能会改变原来的数据,所以必定会刷新缓存!
-
查询不同的Mapper.xml
-
手动清理缓存!
小结:一级缓存默认是开启的,只在一次SqlSession中有效,也就是拿到连接到关闭连接这个区间段!
一级缓存就是一个Map,currentHashMap
3.4、二级缓存
- 二级缓存也叫全局缓存,一级缓存作用域太低了,所以诞生了二级缓存
- 基于namespace级别的缓存,一个名称空间,对应一个二级缓存;
- 工作机制
- 一个会话查询一条数据,这个数据就会被放在当前会话的一级缓存中;
- 如果当前会话关闭了,这个会话对应的一级缓存就没了;但是我们想要的是,会话关闭了,一级缓存中的数据被保存到二级缓存中;
- 新的会话查询信息,就可以从二级缓存中获取内容;
- 不同的mapper查出的数据会放在自己对应的缓存(map)中;
步骤:
-
开启全局缓存
<!--显示的开启全局缓存--> <setting name="cacheEnabled" value="true"/>
-
在要使用二级缓存的Mapper中开启
<!--在当前Mapper.xml中使用二级缓存--> <cache/>
也可以自定义参数
<!--在当前Mapper.xml中使用二级缓存--> <cache eviction="FIFO" flushInterval="60000" size="512" readOnly="true"/>
-
测试
-
问题:我们需要将实体类序列化!否则就会报错!
Caused by: java.io.NotSerializableException: com.kuang.pojo.User
-
小结:
- 只要开启了二级缓存,在同一个Mapper下就有效
- 所有的数据都会先放在一级缓存中;
- 只有当会话提交,或者关闭的时候,才会提交到二级缓冲中!
3.5、缓存原理
3.6、自定义缓存-ehcache
Ehcache是一种广泛使用的开源Java分布式缓存。主要面向通用缓存
要在程序中使用ehcache,先要导包!
<!-- https://mvnrepository.com/artifact/org.mybatis.caches/mybatis-ehcache -->
<dependency>
<groupId>org.mybatis.caches</groupId>
<artifactId>mybatis-ehcache</artifactId>
<version>1.1.0</version>
</dependency>
在mapper中指定使用我们的ehcache缓存实现!
<!--在当前Mapper.xml中使用二级缓存-->
<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>
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="./tmpdir/Tmp_EhCache"/>
<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"/>
<!--
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,最近最少使用的,缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存。
-->
</ehcache>