多对一处理(关联)
CREATE TABLE `teacher` (
`id` INT(10) NOT NULL,
`name` VARCHAR(30) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
INSERT INTO teacher (`id`, `name`) VALUES (1, '秦老师');
CREATE TABLE `student` (
`id` INT(10) 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=utf8;
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('1', '小明', '1');
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('2', '小红', '1');
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('3', '小张', '1');
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('4', '小李', '1');
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('5', '小王', '1');
通过tid外连接,实现学生与老师多对一关系。
public class Teacher {
private int id;
private String name;
}
public class Student {
private int id;
private String name;
//学生需要关联一个老师
private Teacher teacher;
}
测试环境搭建
- 导入lombok
- 新建实体类 Teacher、Student
- 建立Mapper接口
- 建立Mapper.xml文件
- 在核心配置文件中绑定注册Mapper接口
- 测试查询环境是否成功搭建
按照查询嵌套处理
//查询所有学生信息以及对应老师的信息
List<Student> getStudent();
<!-- 思路: 1.查询所有的学生
2.根据查询出来的学生去找对应的老师 -->
<select id="getStudent" resultMap="StudentTeacher">
select * from student;
</select>
<resultMap type="Student" id="StudentTeacher">
<result property="id" column="id" />
<result property="name" column="name" />
<!-- 复杂的数据,需要单独处理
对象:association
集合:collection -->
<association property="teacher" column="tid" javaType="Teacher" select="getTeacher"></association>
</resultMap>
<select id="getTeacher" resultType="Teacher">
select * from teacher where id=#{id}
</select>
按照结果嵌套处理
<!-- 按照结果嵌套处理 -->
<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 type="Student" id="StudentTeacher2">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<association property="teacher" javaType="Teacher">
<result property="name" column="tname"/>
</association>
</resultMap>
对应Mysql中的多对一查询:
- 方法一:子查询
- 方法二:多表联查
一对多处理(集合)
比如:一个老师拥有多个学生,对于老师而言就是一对多的关系
修改环境
public class Student {
private int id;
private String name;
private int tid;
}
public class Teacher {
private int id;
private String name;
//一个老师有多个学生
private List<Student> students;
}
按照查询嵌套处理
//获取指定老师下所有学生及老师的信息
Teacher getTeacher(@Param("tid") int id);
~~~xml
<select id="getTeacher2" resultMap="TeacherStudent2">
select * from mybatis.teacher where id=#{tid}
</select>
<resultMap type="Teacher" id="TeacherStudent2">
<collection property="students" javaType="ArrayList" ofType="Student"
select="getStudentByTeacherId" column="id"/>
</resultMap>
<select id="getStudentByTeacherId" resultType="Student">
select * from mybatis.student where tid=#{id}
</select>
按照结果嵌套处理
<!-- 按结果嵌套查询 -->
<select id="getTeacher" resultMap="TeacherStudent">
select s.id sid, s.name sname, t.name tname,t.id tid
from student s,teacher t
where s.tid=t.id and t.id=#{tid}
</select>
<resultMap type="Teacher" id="TeacherStudent" >
<result property="id" column="tid"/>
<result property="name" column="tname"/>
<!-- 集合中的泛型信息,我们使用ofType处理 -->
<collection property="students" ofType="Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<result property="tid" column="tid"/>
</collection>
</resultMap>
小结
-
association
-
一个复杂类型的关联;许多结果将包装成这种类型
-
嵌套结果映射 – 关联可以是
resultMap
元素,或是对其它结果映射的引用
-
-
collection
-
一个复杂类型的集合
-
嵌套结果映射 – 集合可以是
resultMap
元素,或是对其它结果映射的引用
-
-
JavaType
- 用来指定实体类中属性的类型
-
ofType
- 用来指定映射到List或者集合中的pojo类型(List中的Student)
动态SQL
根据不同的条件生成不同的SQL语句
- if
- choose (when, otherwise)
- trim (where, set)
- foreach
搭建环境
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;
public class Blog {
private int id;
private String title;
private String author;
private Date createTime;
private int view;
}
解决属性名和字段名不一致,开启驼峰命名自动映射:
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
IF判断
//if查询
List<Blog> queryBlogIf(Map map);
//调用
HashMap map=new HashMap();
map.put("title", "Spring");
map.put("author", "狂神说"); //两个参数可以省略
List<Blog> blogs=mapper.queryBlogIf(map);
<select id="queryBlogIf" parameterType="Map" resultType="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>
Where、Set通用
为了避免where and的问题 (自动去掉and) ; 会动态生成where
<select id="queryBlogIf" parameterType="Map" resultType="Blog">
select * from mybatis.blog
<where>
<if test="title!=null">
title=#{title}
</if>
<if test="author!=null">
and author=#{author}
</if>
</where>
</select>
与where类似,解决逗号的问题;会动态生成Set
<update id="updateBlog" parameterType="Map">
update mybatis.blog
<set>
<if test="title!=null">
title=#{title},
</if>
<if test="author!=author">
author=#{author}
</if>
</set>
where id=#{id}
</update>
choose、when、otherwise选择
相当于switch-case,永远只能满足一个条件
List<Blog> queryBlogChoose(Map map);
@test
HashMap map=new HashMap();
map.put("title", "Spring"); //已经命中 when
map.put("author", "狂神说"); //忽略掉第二个when
map.put("views",9999); //忽略掉otherwise这个条件
List<Blog> blogs=mapper.queryBlogIf(map);
<select id="queryBlogChoose" parameterType="Map" resultType="Blog">
select * from mybatis.blog
<where>
<choose>
<when test="title!=null">
title=#{title}
</when>
<when test="author!=author">
author=#{author}
</when>
<otherwise>
views=#{views}
</otherwise>
</choose>
</where>
</select>
trim
如果 where 元素与你期望的不太一样,你也可以通过自定义 trim 元素来定制 where 元素的功能。比如,和 where 元素等价的自定义 trim 元素为:
<trim prefix="WHERE" prefixOverrides="AND |OR "> 前缀
...
</trim>
与 set 元素等价的自定义 trim 元素吧:
<trim prefix="SET" suffixOverrides=","> 后缀
...
</trim>
foreach
动态 SQL 的另一个常见使用场景是对集合进行遍历(尤其是在构建 IN 条件语句的时候)。比如:
//查询第1-2-3号id
List<Blog> queryBlogForeach(Map map);
@Test
ArrayList<Integer> idlist=new ArrayList<Integer>();
idlist.add(1);
idlist.add(2);
idlist.add(3);
HashMap map=new HashMap();
map.put("idlist", idlist); //添加key为idlist的列表
List<Blog> blogs=mapper.queryBlogForeach(map);
<!-- select * from mybatis.blog where 1=1 and (id=1 or id=2 or id=3) -->
<select id="queryBlogForeach" parameterType="Map" resultType="Blog">
select * from mybatis.blog
<where>
<foreach collection="idlist" item="id" open="(" close=")" separator="or">
id=#{id}
</foreach>
</where>
</select>
foreach 元素的功能非常强大,它允许你指定一个集合,声明可以在元素体内使用的集合项(item)和索引(index)变量。它也允许你指定开头与结尾的字符串以及集合项迭代之间的分隔符。这个元素也不会错误地添加多余的分隔符,看它多智能!
提示 你可以将任何可迭代对象(如 List、Set 等)、Map 对象或者数组对象作为集合参数传递给 foreach。当使用可迭代对象或者数组时,index 是当前迭代的序号,item 的值是本次迭代获取到的元素。当使用 Map 对象(或者 Map.Entry 对象的集合)时,index 是键,item 是值。
sql片段
将一部分功能取出来,实现复用!
- 使用SQL标签抽取公共的部分
<sql id="if-title-author">
<if test="title!=null">
title=#{title}
</if>
<if test="author!=null">
and author=#{author}
</if>
</sql>
- 在需要的地方inclue标签引入
<select id="queryBlogIf" parameterType="Map" resultType="Blog">
select * from mybatis.blog
<where>
<include refid="if-title-author"></include>
</where>
</select>
Tips:最好基于单表来定义SQL片段;不要存在where标签
所谓的动态SQL,本质还是SQL语句,只是增加了一个逻辑层面
实际上就是在拼接SQL语句,我们只要保证SQL的正确性,再进行拼接就好了
缓存
- 存在内存中的临时数据(经常查询且不经常改变的数据)
- 多次使用的数据直接查询缓存即可,无需每次都访问数据库,提升效率
Mybatis缓存
默认一级缓存,二级缓存需要手动配置
LRU
– 最近最少使用:移除最长时间不被使用的对象。FIFO
– 先进先出:按对象进入缓存的顺序来移除它们。
一级缓存
- SqlSession级别:作用域为一次会话,也就是拿到连接到关闭连接
- 也叫本地缓存:与数据库同义词会话期间查询到的数据会放在本地缓存中
- 一级缓存就是一个Map
测试:在同一个session会话中,连续两次查询同一条记录,并观察日志输出
public void queryUserById() {
SqlSession sqlSession = MybatisUtils.getsqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user=mapper.queryUserById(1);
System.out.println(user);
System.out.println("=======================================");
User user2=mapper.queryUserById(1);
System.out.println(user2);
System.out.println(user==user2); //对象地址
sqlSession.close();
}
缓存失效的情况:
- 增删改操作,可能会改变原来的数据,所以必定会刷新缓存
- 两次查询的结果不同
- 查询不同Mapper里的东西
- 手动清理缓存 sqlSession.clearCache();
二级缓存
- 全局缓存:提升一级缓存的作用域
- namespace级别:一个名称空间,对应一个二级缓存
测试:
- 开启全局缓存
<!-- 显式开启缓存 -->
<setting name="cacheEnabled" value="true"/>
- 默认情况下,只启用了本地的会话缓存,它仅仅对一个会话中的数据进行缓存。 要启用全局的二级缓存,只需要在你的 SQL 映射文件中添加一行:
<cache/>
<cache
eviction="FIFO"
flushInterval="60000"
size="512"
readOnly="true"/>
这个更高级的配置创建了一个 FIFO 缓存,每隔 60 秒刷新,最多可以存储结果对象或列表的 512 个引用,而且返回的对象被认为是只读的,因此对它们进行修改可能会在不同线程中的调用者产生冲突。
- 测试:序列化实体类
public void queryUserById2() {
SqlSession sqlSession = MybatisUtils.getsqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user=mapper.queryUserById(1);
System.out.println(user);
sqlSession.close();
System.out.println("=======================================");
SqlSession sqlSession2 = MybatisUtils.getsqlSession();
UserMapper mapper2 = sqlSession2.getMapper(UserMapper.class);
User user2=mapper2.queryUserById(1);
System.out.println(user2);
System.out.println(user==user2); //对象地址都相同
sqlSession2.close();
}
小结:
- 只要开启了二级缓存,在同一个Mapper下就有效
- 所有的数据都会先放在一级缓存中
- 只有当会话提交或关闭的时候,才会提交到耳机缓存
原理图
自定义缓存-ehcache
EhCache 是一个纯Java的进程内缓存框架,具有快速、精干等特点,用于通用缓存
- 导包
<!-- ehcache-mybatis -->
<dependency>
<groupId>org.mybatis.caches</groupId>
<artifactId>mybatis-ehcache</artifactId>
<version>1.0.3</version>
</dependency>
- 在mapper.xml中选中自己的cache
<!-- 自定义缓存,在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 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"/>
</ehcache>
实际上都用:Redis来做缓存,效率更高