SSM框架——Mybatis(7)延迟加载和立即加载

Mybatis的延迟加载和立即加载

  • 延迟加载:在真正使用数据时才发起查询,不用的时候不查询。按需加载(懒加载)
  • 立即加载:不管用不用,只要一调用方法,马上发起查询。
  • 在对应的四种表关系中:一对多,多对一,一对一,多对多
    • 一对多,多对多:通常情况下都采用延迟加载。
    • 多对一,一对一:通常情况下都采用立即加载。
  • 在进行配置之前需要配置SqlMapConfig.xml的参数
    <settings>
        <setting name="lazyLoadingEnabled" value="true"/>
        <setting name="aggressiveLazyLoading" value="false"/>
    </settings>

一对一的延迟加载

  • 在配置文件中进行配置工作
    <!-- 定义封装account和user的resultMap -->
    <resultMap id="accountMap" type="com.mybatis.Account">
        <id property="id" column="aid"></id>
        <result property="uid" column="uid"></result>
        <result property="money" column="money"></result>
        <!-- 一对一的关系映射:配置封装user的内容
        select的属性指定的内容:查询用户的唯一内容
        column的属性指定的内容:用户根据id查询时,所需要的参数的值
        -->
        <association property="user" column="uid" javaType="com.mybatis.User" select="com.mybatis.dao.UserDao.findById">
        </association>
    </resultMap>
  • 测试用例
    @Test
    public void TestfindAll(){
        //5.使用代理方法执行查询所有的方法
        List<Account> accounts =accountDao.findAll();
        for(Account account:accounts){
            System.out.println("------------------");
            System.out.println(account);
        }
    }
  • 这就是延迟加载。在从表中是多的话,一般都使用一对一。

一对多的延迟加载

  • 在配置文件中进行配置工作
    <!-- 定义User的resultMap -->
    <resultMap id="userAccountMap" type="com.mybatis.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="com.mybatis.Account" select="com.mybatis.dao.AccountDao.findAccountByUid" column="id">
        </collection>
    </resultMap>  
  • 测试用例
    @Test
    public void TestfindAll(){
        //5.使用代理方法执行查询所有的方法
        List<User> users=userDao.findAll();
        for(User user:users){
            System.out.println("------------------------");
            System.out.println(user);
        }
    }

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值