Mysql延迟加载及一二级缓存

一、延迟加载

实际开发过程中很多时候我们并不需要总是在加载用户信息时就一定要加载他的账户信息。 此时就是我们所说的延迟加载

延迟加载:

就是在需要用到数据时才进行加载,不需要用到数据时就不加载数据。

延迟加载也称懒加载

好处: 先从单表查询,需要时再从关联表去关联查询,大大提高数据库性能,因为查询单表要比关联查询多张表速度要快

坏处:因为只有当需要用到数据时,才会进行数据库查询,这样在大批量数据查询时,因为查询工作也要消耗时间,所以可能造成用户等待时间变长,造成用户体验下降。

 使用mybatis时,使用association和collection可以实现字段扩展,子表相关功能实现延迟加载,

  • 多对一关系 —— association
    二、一对多关系 —— collection

一对一关系(多对一关系):

例如:

多对一:一个班50名都有一个班主任老师,即多名同学关联一位老师。

一对多:一名班主任老师管理班里50个同学,即一个集合概念。

针对于上述情况,若想查询某些同学共有的老师是谁,或者一名老师带了多少位同学,则需进行老师信息表teacher与学生信息表student联表查询,就会用到下面介绍的association和collection关键词。

一、多对一关系 —— association

 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');

对于接口的实现:

基于子查询的:

SELECT student.id, student.name, student.tid
FROM student
WHERE student.tid = ( SELECT teacher.id FROM teacher )

基于结果查询的:

SELECT s.id,s.name,s.tid,t.name FROM student AS s,teacher AS t
WHERE t.id = s.tid

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE mapper

        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"

        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<!-- 绑定对应Mapper接口 -->

<mapper namespace="com.ali.mapper.StudentMapper">

<!--    1.按照查询嵌套处理->子查询 -->

    <select id="getStudents" resultMap="studentMap" resultType="com.ali.pojo.Student">

        select * from mybatis.student

    </select>

    <resultMap id="studentMap" type="com.ali.pojo.Student">

        <result property="id" column="id"></result>

        <result property="name" column="name"></result>

        <association property="teacher" column="tid" javaType="com.ali.pojo.Teacher" select="getTeachers"></association>

    </resultMap>

    <select id="getTeachers" resultType="com.ali.pojo.Teacher">

        select * from mybatis.teacher where id = #{id}

    </select>

<!--    2.按照结果查询->嵌套查询-->

    <select id="getStudents" resultMap="studentMapper">

        select s.id sid, s.name sname, t.id tid, t.name tname

        from mybatis.student s,mybatis.teacher t

        where s.tid = t.id;

    </select>

    <resultMap id="studentMapper" type="com.ali.pojo.Student">

        <result property="id" column="sid"></result>

        <result property="name" column="sname"></result>

        <result property="tid" column="stid"></result>

        <association property="teacher" javaType="com.ali.pojo.Teacher">

            <result property="id" column="tid"></result>

            <result property="name" column="tname"></result>

        </association>

    </resultMap>

</mapper>

 一对多关系:

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE mapper

        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"

        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<!-- 绑定对应Mapper接口 -->

<mapper namespace="com.ali.mapper.TeacherMapper">

<!--    1.基于子查询实现-->

    <select id="getTeacher1" resultMap="teacherMap">

        select * from mybatis.teacher

        where mybatis.teacher.id = #{id}

    </select>

    <resultMap id="teacherMap" type="com.ali.pojo.Teacher">

        <result property="name" column="name"></result>

        <collection property="students" column="id" javaType="ArrayList" ofType="com.ali.pojo.Student" select="studentMap">

        </collection>

    </resultMap>

    <select id="studentMap" resultType="com.ali.pojo.Student">

        select * from mybatis.student where tid = #{id};

    </select>

    

<!--    2. 基于结果查询实现-->

    <select id="getTeacher" resultMap="teacherInfo">

        select s.id,s.name,t.id tid,t.name

        from mybatis.student s, mybatis.teacher t

        where t.id = s.tid and t.id = #{id}

    </select>

    <resultMap id="teacherInfo" type="com.ali.pojo.Teacher">

        <result property="id" column="id"></result>

        <result property="name" column="name"></result>

        <collection property="students" ofType="com.ali.pojo.Student">

            <result property="id" column="id"></result>

            <result property="name" column="name"></result>

            <result property="tid" column="tid"></result>

        </collection>

    </resultMap>

</mapper>

 

二、Mybatis缓存

像大多数的持久化框架一样, Mybatis 也提供了缓存策略,通过缓存策略来减少数据库的查询次数, 从而提高性能

Mybatis 中缓存分为一级缓存,二级缓存

2.1 一级缓存

一级缓存是 SqlSession 级别的缓存,只要 SqlSession 没有 flush 或 close,它就存在

2.1.1 实现

public class UserTest {

    private InputStream in;

    private SqlSession sqlSession;

    private IUserDao dao;

    //执行前运行

    @Before

    public void init() throws IOException {

        in = Resources.getResourceAsStream("SqlMapConfig.xml");

        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);

        sqlSession = factory.openSession();

        dao = sqlSession.getMapper(IUserDao.class);

    }

    //执行后回收

    @After

    public void destroy() throws IOException {

        sqlSession.close();

        in.close();

    }

    //测试一级缓存

    @org.junit.Test

    public void testFirstLevelCache() {

        User user1 = dao.findById(41);

        System.out.println(user1);

        //如果清除缓存,user1和user2就不是同一个对象了

        sqlSession.clearCache();

        User user2 = dao.findById(41);

        System.out.println(user2);

        //如果不清除缓存 user1会等于user2 只发起一次查询

        System.out.println(user1 == user2);

    }

    //测试缓存同步

    @org.junit.Test

    public void testClearCache() {

        User user1 = dao.findById(41);

        user1.setUsername("哈哈");

        user1.setAddress("纽约");

        //更新id=41的客户

        dao.updateUser(user1);

        sqlSession.commit();

        //再次查id=41

        User user2 = dao.findById(41);

        System.out.println(user1 == user2);

    }

-----------------------------------

mysql 操作延时 mysql延迟加载

我们可以发现,虽然在上面的代码中我们查询了两次,但最后只执行了一次数据库操作.这就是 Mybatis 提供给我们的一级缓存在起作用了。

因为一级缓存的存在,导致第二次查询 id 为 41 的记录时,并没有发出 sql 语句从数据库中查询数据,而是从一级缓存中查询。

2.1.2 一级缓存的分析

一级缓存是 SqlSession 范围的缓存,当调用 SqlSession 的修改,添加,删除, commit(), close()等方法时,就会清空一级缓存。

第一次发起查询用户 id 为 1 的用户信息,先去找缓存中是否有 id 为 1 的用户信息如果没有,从数据库查询用户信息。

得到用户信息,将用户信息存储到一级缓存中。

如果 sqlSession 去执行 commit 操作(执行插入、更新、删除),清空 SqlSession中的一级缓存,这样做的目的为了让缓存中存储的是最新的信息,避免脏读

第二次发起查询用户 id 为 1 的用户信息,先去找缓存中是否有 id 为 1 的用户信息,缓存中有,直接从缓存中获取用户信息

2.1.3 缓存的同步

当执行更新操作后后,再次获取sqlSession并查询id=41的User对象时,又重新执行了sql语句,从数据库进行了查询操作。

//测试缓存同步

@org.junit.Test

public void testClearCache() {

    User user1 = dao.findById(41);

    user1.setUsername("哈哈");

    user1.setAddress("纽约");

    //更新id=41的客户

    dao.updateUser(user1);

    sqlSession.commit();

    //再次查id=41

    User user2 = dao.findById(41);

    System.out.println(user1 == user2);

}

2.2 二级缓存

二级缓存是 mapper 映射级别的缓存,多个 SqlSession 去操作同一个 Mapper 映射的sql 语句,多个SqlSession 可以共用二级缓存,二级缓存是跨 SqlSession 的 。

2.2.1 缓存结构

 

sqlSession1 去查询用户信息,查询到用户信息会将查询数据存储到二级缓存中

如果 SqlSession3 去执行相同 mapper 映射下 sql,执行 commit 提交, 将会清空该mapper 映射下的二级缓存区域的数据

如果 SqlSession3 去执行相同 mapper 映射下 sql,执行 commit 提交, 将会清空该mapper 映射下的二级缓存区域的数据

2.2.2 开启二级缓存

SqlMapConfig.xml 文件配置

<settings>

<!-- 开启二级缓存的支持 -->

<setting name="cacheEnabled" value="true"/>

</settings>

因为 cacheEnabled 的取值默认就为 true,所以这一步可以省略不配置。为 true 代表开启二级缓存;为false 代表不开启二级缓存

Mapper 映射文件配置

<cache>标签表示当前这个 mapper 映射将使用二级缓存,区分的标准就看 mapper 的 namespace 值。

<mapper namespace="dao.IUserDao">

<!-- 开启二级缓存的支持 -->

<cache></cache>

</mapper>

配置 statement 上面的 useCache 属性

<!-- 根据 id 查询 -->

<select id="findById" resultType="user" parameterType="int" useCache="true">

select * from user where id = #{uid}

</select>

将 UserDao.xml 映射文件中的<select>标签中设置 useCache=”true”代表当前这个 statement 要使用二级缓存,

如果不使用二级缓存可以设置为 false。

注意: 针对每次查询都需要最新的数据 sql,要设置成 useCache=false,禁用二级缓存。

2.2.3 注意事项

当我们在使用二级缓存时,所缓存的类一定要实现 java.io.Serializable 接口,这种可以使用序列化方式来保存对象

public class User implements Serializable {

private Integer id;

private String username;

private Date birthday;

private String sex;

private String address;

}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值