Mybatis中的延迟加载和缓存

往期内容,如下
一、MyBatis简介
二、MyBatis环境搭建
三、MyBatis入门案例
四、MyBatis自定义
五、MyBatis CRUD操作
六、Mybatis中参数和返回值的深入了解
七、MyBatis 配置文件标签
八、MyBatis POOLED连接池深入了解
九、MyBatis中的动态sql语句
十、MyBatis多表查询操作

延迟加载和立即加载

延迟加载:

  • 在真正使用数据时才发起查询,不用的时候不查询。按需加载,即使懒加载

立即加载:

  • 不管用不用,只要一调用方法,马上发起查询。

在对应的四种表关系中:一对多,多对一,一对一,多对多

  • 一对多、多对多:通常采用延迟加载
  • 多对一、一对一:通常采用立即加载

环境搭建:

最终代码目录结构如下:
在这里插入图片描述
配置文件pom.xml log4j.properties jdbcConfig.properties SqlMapConfig.xml 实体类User、Account 接口IUserDaoMyBatis多表查询操作环境搭建一样,这里不在赘述

接口

com.itheima.dao.IAccountDao

package com.itheima.dao;

import com.itheima.domain.Account;

import java.util.List;

public interface IAccountDao {

    /**
     * 查询所有账户,同时还要获取到当前账户的所属用户信息
     * @return
     */
    List<Account> findAll();

}
配置文件:

com/itheima/dao/IAccountDao.xml

<?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 namespace="com.itheima.dao.IAccountDao">

    <!-- 定义封装account和user的resultMap -->
    <resultMap id="accountUserMap" type="account">
        <id property="id" column="id"></id>
        <result property="uid" column="uid"></result>
        <result property="money" column="money"></result>
    </resultMap>

    <!-- 查询所有 -->
    <select id="findAll" resultMap="accountUserMap">
        select * from account 
    </select>
</mapper>
测试类:

com.itheima.test.AccountTest

package com.itheima.test;

import com.itheima.dao.IAccountDao;
import com.itheima.domain.Account;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.InputStream;
import java.util.List;

public class AccountTest {

    private InputStream in;
    private SqlSession sqlSession;
    private IAccountDao accountDao;

    @Before//用于在测试方法执行之前执行
    public void init()throws Exception{
        //1.读取配置文件,生成字节输入流
        in = Resources.getResourceAsStream("SqlMapConfig.xml");
        //2.获取SqlSessionFactory
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        //3.获取SqlSession对象
        sqlSession = factory.openSession(true);
        //4.获取dao的代理对象
        accountDao = sqlSession.getMapper(IAccountDao.class);
    }

    @After//用于在测试方法执行之后执行
    public void destroy()throws Exception{
        //提交事务
        // sqlSession.commit();
        //6.释放资源
        sqlSession.close();
        in.close();
    }

    /**
     * 测试查询所有
     */
    @Test
    public void testFindAll(){
        List<Account> accounts = accountDao.findAll();
        for(Account account : accounts){
            System.out.println("--------每个account的信息------------");
            System.out.println(account);
            System.out.println(account.getUser());
        }
    }


}

运行测试类方法testFindAll(),结果如下:
在这里插入图片描述

如何使用延迟加载

使用<association>标签

属性:

  • select:属性指定的内容:查询用户的唯一标识
  • column:属性指定的内容:用户根据id查询时,所需要的参数的值

在Mybatis配置文件中使用<association>标签

在Mybatis配置文件中开启延迟加载

<configuration>
    <!--配置参数-->
    <settings>
        <!--开启Mybatis支持延迟加载-->
        <setting name="lazyLoadingEnabled" value="true"/>
        <setting name="aggressiveLazyLoading" value="false"></setting>
    </settings>
</configuration>

一对一延迟加载

这个时候只需修改com/itheima/dao/IAccountDao.xml

<?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 namespace="com.itheima.dao.IAccountDao">

    <!-- 定义封装account和user的resultMap -->
    <resultMap id="accountUserMap" type="account">
        <id property="id" column="id"></id>
        <result property="uid" column="uid"></result>
        <result property="money" column="money"></result>
        <!-- 到IUserDao.xml的findById -->
        <association property="user" column="uid" javaType="user" select="com.itheima.dao.IUserDao.findById"></association>
    </resultMap>

    <!-- 查询所有 -->
    <select id="findAll" resultMap="accountUserMap">
        select * from account
    </select>
</mapper>

com/itheima/dao/IUserDao.xml

<?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 namespace="com.itheima.dao.IUserDao">

    <!-- 定义User的resultMap-->
    <resultMap id="userAccountMap" type="user">
        <id property="id" column="id"></id>
        <result property="username" column="username"></result>
        <result property="address" column="address"></result>
        <result property="sex" column="sex"></result>
        <result property="birthday" column="birthday"></result>
        <!-- 配置user对象中accounts集合的映射 -->
        <collection property="accounts" ofType="account" select="com.itheima.dao.IAccountDao.findAccountByUid" column="id"></collection>
    </resultMap>

    <!-- 查询所有 -->
    <select id="findAll" resultMap="userAccountMap">
        select * from user
    </select>

    <!-- 根据id查询用户 -->
    <select id="findById" parameterType="INT" resultType="user">
        select * from user where id = #{uid}
    </select>

</mapper>

开启延迟加载

<configuration>
    <!--配置参数-->
    <settings>
        <!--开启Mybatis支持延迟加载-->
        <setting name="lazyLoadingEnabled" value="true"/>
        <setting name="aggressiveLazyLoading" value="false"></setting>
    </settings>
</configuration>

运行测试类com.itheima.test.AccountTest.testFindAll方法,结果如下:
在这里插入图片描述

一对多延迟加载

修改com/itheima/dao/IUserDao.xml

<?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 namespace="com.itheima.dao.IUserDao">

    <!-- 定义User的resultMap-->
    <resultMap id="userAccountMap" type="user">
        <id property="id" column="id"></id>
        <result property="username" column="username"></result>
        <result property="address" column="address"></result>
        <result property="sex" column="sex"></result>
        <result property="birthday" column="birthday"></result>
        <!-- 配置user对象中accounts集合的映射 -->
        <collection property="accounts" ofType="account" select="com.itheima.dao.IAccountDao.findAccountByUid" column="id"></collection>
    </resultMap>

    <!-- 查询所有 -->
    <select id="findAll" resultMap="userAccountMap">
        select * from user
    </select>

</mapper>

com/itheima/dao/IAccountDao.xml

<?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 namespace="com.itheima.dao.IAccountDao">

    <!-- 定义封装account和user的resultMap -->
    <resultMap id="accountUserMap" type="account">
        <id property="id" column="id"></id>
        <result property="uid" column="uid"></result>
        <result property="money" column="money"></result>
        <association property="user" column="uid" javaType="user" select="com.itheima.dao.IUserDao.findById"></association>
    </resultMap>

    <!-- 查询所有 -->
    <select id="findAll" resultMap="accountUserMap">
        select * from account
    </select>

    <!-- 根据用户id查询账户列表 -->
    <select id="findAccountByUid" resultType="account">
        select * from account where uid = #{id}
    </select>

</mapper>

在接口IAccountDao加一个方法
com.itheima.dao.IAccountDao


    /**
     * 根据用户id查询账户信息
     * @param uid
     * @return
     */
    List<Account> findAccountByUid(Integer uid);

修改com/itheima/dao/IAccountDao.xml

    <!-- 根据用户id查询账户列表 -->
    <select id="findAccountByUid" resultType="account">
        select * from account where uid = #{uid}
    </select>

运行测试类方法,结果如下
com.itheima.test.UserTesttestFindAll方法
在这里插入图片描述

缓存

什么是缓存

  • 存在于内存中的临时数据

为什么使用缓存

  • 减少和数据库的交互次数,提高执行效率

适用于缓存

  • 经常查询并且不经常改变的
  • 数据的正确与否对最终结果影响不大的

不适用于缓存

  • 经常改变的数据
  • 数据的正确与否对最终结果影响很大的(商品的库存,银行的汇率,股市的牌价)

一级缓存

  • 它指的是Mybatis中SqlSession对象的缓存,当我们执行查询之后,查询的结果会同时存入到SqlSession为我们提供一块区域中该区域的结构是一个Map。当我们再次查询同样的数据,Mybatis会先去sqlsession中查询是否有,有的话直接拿出来用。当SqlSession对象消失时,Mybatis的一级缓存也就消失了
  • 一级缓存是Mybatis默认开启的
  • 一级缓存是SqlSession范围的缓存,当调用SqlSeesion修改添加删除commit()close()等方法时,一级缓存就会清空

二级缓存

  • 它指的是Mybatis中SqlSessionFactory对象的缓存,由同一个SqlSessionFactory对象创建的SqlSession共享其缓存

二级缓存的使用步骤

  1. 让Mybatis框架支持二级缓存(在SqlMapConfig.xml中配置)
<settings>
	<setting name="cacheEnabled" value="true" />
</settings>
  1. 让当前的映射文件支持二级缓存(在IUserDao.xml中配置)
<!-- 开启User支持二级缓存-->
<cache/>
  1. 让当前的操作支持二级缓存(在select标签中配置)
<select id="findById" paramterType="int" resultType="user" useCache="true">
	select * from user where id = #{uid}
</select>

注意:二级缓存存放的并不是对象,而是数据,谁需要用就从里面取出数据填充到不同的对象中,所以对象并不一样

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值