mybatis 一对多的延迟加载

本文详细介绍了如何在MyBatis中配置延迟加载和一对一关系映射,通过修改主配置文件设置延迟加载选项,并在UserDao.xml中定义User的resultMap,包括accounts集合的映射。同时展示了IAccountDao.xml中对应的Account resultMap和查询方法,实现了用户和账户之间的关联映射。通过对这两个DAO的配置,可以有效地管理和加载关联数据,提高查询效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

案例:

一的一方:user
多的一方:account
在这里插入图片描述

主配置文件的修改

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

IuserDao.xml 修改

 <!-- 定义User的resultMap-->
    <resultMap id="userAccountMapLazy" 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="hellomybaits.dao.IAccountDao.findAccountByUid"
                    column="id"></collection>
    </resultMap>


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

 <select id="findById" resultType="hellomybaits.domain.User">
        select * from user where id = #{uid}

    </select>

IAccountDao.xml

<resultMap id="accoutMapLazy" 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="hellomybaits.dao.IUserDao.findById"></association>
    </resultMap>
<select id="findAccountByUid" resultType="hellomybaits.domain.Account">

    select * from account where uid = #{uid}
</select>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值