mybatis学习笔记(四)
9. 多对一处理
-
多个学生关联一个老师(多对一)
-
集合(一对多)
1. 建表
CREATE TABLE `teacher` (
`id` INT(10) NOT NULL PRIMARY KEY,
`name` VARCHAR(30) DEFAULT NULL
)ENGINE=INNODB DEFAULT CHARSET=utf8
INSERT INTO teacher (`id`, `name`) VALUES (1, 'tzy');
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, 'ntu1', 1);
INSERT INTO student (`id`, `name`, `tid`) VALUES (2, 'ntu2', 1);
INSERT INTO student (`id`, `name`, `tid`) VALUES (3, 'ntu3', 1);
INSERT INTO student (`id`, `name`, `tid`) VALUES (4, 'ntu4', 1);
INSERT INTO student (`id`, `name`, `tid`) VALUES (5, 'ntu5', 1);
-
新建实体类
package tzy.tzytry.pojo; import lombok.Data; @Data public class Student { private int id; private String name; //学生需要关联一个老师 private Teacher teacher; }package tzy.tzytry.pojo; import lombok.Data; @Data public class Teacher { private int id; private String name; } -
建立Mapper接口
-
建立Mapper.xml
-
测试是否能够成功
2. 按照查询嵌套处理
StudentMapper.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.StudentMapper">
<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 = #{id};
</select>
</mapper>
3. 按照结果嵌套处理
select s.id,s.name sname,t.id tid,t.name tname from mybatis.teacher t,mybatis.student s
where s.tid=t.id;
<select id="getStudent2" resultMap="StudentTeacher2">
select s.id,s.name sname,t.id tid,t.name tname from mybatis.teacher t,mybatis.student s
where s.tid=t.id;
</select>
<resultMap id="StudentTeacher2" type="student">
<result property="id" column="id"/>
<result property="name" column="sname"/>
<association property="teacher" javaType="Teacher">
<result property="name" column="tname"/>
<result property="id" column="tid"/>
</association>
</resultMap>
property 映射到列结果的字段或属性。
column 数据库中的列名,或者是列的别名。
10. 一对多
一个老师拥有多个学生
对于老师而言就是一对多
1.环境搭建
实体类
package com.hou.pojo;
import lombok.Data;
import java.util.List;
@Data
public class Teacher {
private int id;
private String name;
private List<Student> studentList;
}
package com.hou.pojo;
import lombok.Data;
@Data
public class Student {
private int id;
private String name;
private int tid;
}
2. 按照结果查询
<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 = #{id};
</select>
<resultMap id="TeacherStudent" type="com.hou.pojo.Teacher">
<result property="id" column="tid"></result>
<result property="name" column="tname"></result>
<!--集合中的泛型信息,我们用oftype获取-->
<collection property="studentList" ofType="com.hou.pojo.Student">
<result property="id" column="sid"></result>
<result property="name" column="sname"></result>
</collection>
</resultMap>
3. 按照查询嵌套处理
<select id="getTeacher2" resultMap="TeacherStudent2">
select * from mybatis.teacher where id = #{id}
</select>
<resultMap id="TeacherStudent2" type="com.hou.pojo.Teacher">
<collection property="studentList" column="id" javaType="ArrayList"
ofType="com.hou.pojo.Student"
select="getStudentByTeacherId"></collection>
</resultMap>
<select id="getStudentByTeacherId" resultType="com.hou.pojo.Student">
select * from mybatis.student where tid = #{id}
</select>
小结
- 关联 - association 多对一
- 集合 - collection 一对多
- javaType & ofType
- JavaType用来指定实体中属性类型
- ofType映射到list中的类型,泛型中的约束类型
注意点:
- 保证sql可读性,尽量保证通俗易懂
- 注意字段问题
- 如果问题不好排查错误,使用日志
面试高频:
- Mysql引擎
- InnoDB底层原理
- 索引
- 索引优化!
11. 动态sql
动态sql:根据不同的条件生成不同的SQL语句
动态SQL就是在拼接SQL语句,我们只要保证SQL的正确性,按照SQL的格式,去排列组合就行了
建议:
- 先在Mysql中写出完整的SQL,再对应去修改成为我们的动态SQL实现通用即可!
在 MyBatis 之前的版本中,需要花时间了解大量的元素。借助功能强大的基于 OGNL 的表达式,MyBatis 3 替换了之前的大部分元素,大大精简了元素种类,现在要学习的元素种类比原来的一半还要少。
if
choose (when, otherwise)
trim (where, set)
foreach
1. 搭建环境
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
实体类
package com.hou.pojo;
import lombok.Data;
import java.util.Date;
@Data
public class Blog {
private String id;
private String title;
private String author;
private Date createTime;
private int views;
}
核心配置
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
Mapper.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.mapper.BlogMapper">
<insert id="addBlog" parameterType="Blog">
insert into mybatis.blog (id, title, author, create_time, views) values
(#{id}, #{title}, #{author}, #{create_time}, #{views});
</insert>
</mapper>
新建随机生成ID包
package tzy.tzytry.utils;
import org.junit.Test;
import java.util.UUID;
@SuppressWarnings("all")//抑制警告
public class IDUtiles {
public static String getId(){
return UUID.randomUUID().toString().replaceAll("-","");
}
@Test
public void test(){
System.out.println(getId());
}
}
测试类:添加数据
package tzy.tzytry.Dao;
import tzy.tzytry.pojo.Blog;
import tzy.tzytry.utils.IDutils;
import tzy.tzytry.utils.mybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.Date;
public class MyTest {
@Test
public void addBlog(){
SqlSession sqlSession = mybatisUtils.getSqlSession();
BlogMapper blogMapper = sqlSession.getMapper(BlogMapper.class);
Blog blog = new Blog();
blog.setId(IDutils.getId());
blog.setAuthor("tzy");
blog.setCreateTime(new Date());
blog.setViews(999);
blog.setTitle("first");
blogMapper.addBolg(blog);
blog.setId(IDutils.getId());
blog.setTitle("second");
blogMapper.addBolg(blog);
blog.setId(IDutils.getId());
blog.setTitle("third");
blogMapper.addBolg(blog);
blog.setId(IDutils.getId());
blog.setTitle("forth");
blogMapper.addBolg(blog);
sqlSession.close();
}
}
2. if
<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 != author">
and author = #{author}
</if>
</select>
test
@Test
public void queryBlogIF(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper blogMapper = sqlSession.getMapper(BlogMapper.class);
Map map = new HashMap();
// map.put("title", "second");
map.put("author", "houdongun");
List<Blog> list = blogMapper.queryBlogIF(map);
for (Blog blog : list) {
System.out.println(blog);
}
sqlSession.close();
}
3. 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>
4. trim、where、set
where自动去除and|or,set自动去除","
<select id="queryBlogIf" parameterType="map" resultType="blog">
select * from mybatis.blog
<where>
<if test="title!=null">
and title=#{title}
</if>
<if test="author!=null">
and author=#{author}
</if>
</where>
</select>
<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 可以自定义:
1where 元素只会在子元素返回任何内容的情况下才插入 “WHERE” 子句。而且,若子句的开头为 “AND” 或 “OR”,where 元素也会将它们去除。
如果 where 元素与你期望的不太一样,你也可以通过自定义 trim 元素来定制 where 元素的功能。比如,和 where 元素等价的自定义 trim 元素为:
<trim prefix="WHERE" prefixOverrides="AND |OR ">
...
</trim>
2.set 元素会动态地在行首插入 SET 关键字,并会删掉额外的逗号(这些逗号是在使用条件语句给列赋值时引入的)。
来看看与 set 元素等价的自定义 trim 元素吧:
<trim prefix="SET" suffixOverrides=",">
...
</trim>
注意,我们覆盖了后缀值设置,并且自定义了前缀值。
SQL片段
有些时候我们有一些公共部分
-
使用sql便签抽取公共部分
-
在使用的地方使用include标签
<sql id="if-title-author">
<if test="title != null">
title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</sql>
<select id="queryBlogIF" parameterType="map" resultType="Blog">
select * from mybatis.blog
<where>
<include refid="if-title-author"></include>
</where>
</select>
注意:
- 最好基于单表
- sql里不要存在where标签
5. for-each
<!--ids是传的,#{id}是遍历的-->
<select id="queryBlogForeach" parameterType="map" resultType="Blog">
select * from mybatis.blog
<where>
<foreach collection="ids" item="id" open="and ("
close=")" separator="or">
id=#{id}
</foreach>
</where>
</select>
test
@Test
public void queryBlogForeach(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper blogMapper = sqlSession.getMapper(BlogMapper.class);
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);
for (Blog blog : list) {
System.out.println(blog);
}
sqlSession.close();
}
12. 缓存(了解)
1.什么是缓存?
- 存在内存中的临时数据
- 将用户经常查询的数据放在缓存(内存)中,用户去查询数据就不用从磁盘上(关系型数据库数据文件)查询,从缓存中查询,从而提高查询效率,解决了高并发系统的新能问题
2.为什么使用缓存?
- 减少和数据库的交互次数,减小系统开销,提高系统效率
3.什么样的数据能使用缓存?
- 经常查询并且不经常改变的数据【可以使用缓存】
1. 一级缓存
- 开启日志(必须)
- 测试一个session中查询两次相同记录。
缓存失效:
- *映射语句文件中的所有 insert、update 和 delete 语句会刷新缓存。
- *查询不同的mapper.xml
- *手动清除缓存
sqlSession.clearCache(); //手动清理缓存
一级缓存默认开启,只在一次sqlseesion中有效,也就是拿到连接和关闭连接这段区间段,可以理解为一级缓存就是一个map
2. 二级缓存
- 开启全局缓存
<setting name="cacheEnabled" value="true"/>
- 在当前mapper.xml中使用二级缓存(后面参数可加可不加)
<cache eviction="FIFO"
flushInterval="60000"
size="512"
readOnly="true"/>
test
@Test
public void test(){
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();
UserMapper userMapper1 = sqlSession1.getMapper(UserMapper.class);
User user1 = userMapper1.queryUserByid(1);
System.out.println(user1);
System.out.println(user==user1);
sqlSession1.close();
}
只用cache时加序列化
<cache/>
//示例:实现Serializable(可序列化),对实体类实现!
@Data
@AllArgsConstructor //有参构造
@NoArgsConstructor //无参构造
public class User implements Serializable {
private int id;
private String name;
private String pwd;
}
实体类
package com.hou.pojo;
import lombok.Data;
import java.io.Serializable;
@Data
public class User implements Serializable {
private int id;
private String name;
private String pwd;
public User(int id, String name, String pwd) {
this.id = id;
this.name = name;
this.pwd = pwd;
}
}
小结:
- 只有开启了二级缓存,在Mapper下有效
- 所有数据都会先放在一级缓存
- 只有当回话提交,或者关闭的时候,才会提交到二级缓存(即当一级缓存结束时候,数据会传到二级缓存,下一个一级缓存开始并查询时候,查的内容一致会自动读取二级缓存里的内容)
3. 自定义缓存-ehcache
导入包
<!-- https://mvnrepository.com/artifact/org.mybatis.caches/mybatis-ehcache -->
<dependency>
<groupId>org.mybatis.caches</groupId>
<artifactId>mybatis-ehcache</artifactId>
<version>1.2.1</version>
</dependency>
设置缓存(在mapper中指定使用我们的ehcache缓存实现)
<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="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>
Redis数据库来做缓存 K-V

浙公网安备 33010602011771号