mybatis延迟加载

1、什么是延迟加载

在使用时候才加载数据,不用的时候不加载

2、关联对象是1时,采用立即加载;

      关联对象是多是,采用延迟加载

3、一对一(一对多)延迟加载步骤及配置

(1)SqlMapConfig.xml

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

(2)IUserdao.xml

   <!-- 定义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>

(3)IAccountDao.xml

    <!-- 定义封装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>
        <!-- 一对一的关系映射:配置封装user的内容
        select属性指定的内容:查询用户的唯一标识:
        column属性指定的内容:用户根据id查询时,所需要的参数的值
        -->
        <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 = #{uid}
    </select>

4、缓存概念

适用缓存情况:

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

不适用缓存情况:

   经常查询并且经常改变的数据,数据正确与否对最终结果影响很大,商品库存,银行牌价

(1)一级缓存

是SQLSession对象的缓存,查询结果同时存入一级缓存,数据结构是Map,先查询一级缓存,然后再查询其它。SQLSession消失,一级缓存也消失

(2)二级缓存

是SQLSessionFactory对象的缓存,由同一个SQLSessionFactory对象创建的SqlSession共享缓存

使用步骤:让mybatis支持二级缓存(在SqlMapConfig.xml中配置)

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

                  让当前的映射文件支持二级缓存(在IUserDao.xml中配置)

 <!--开启user支持二级缓存-->
    <cache/>

                 让当前的操作支持二级缓存(在select标签中配置)

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

 

 

 

 

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值