JAVAEE细细看 框架12 - Mybatis 多表操作延迟加载

本文详细介绍了MyBatis框架下的一对一和一对多表操作配置方法,以及如何实现延迟加载来优化数据查询效率。通过具体的XML映射文件示例,展示了如何使用association和collection标签进行关联查询,同时解释了立即加载与延迟加载的区别。

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

MyBatis多表操作延迟加载

1. 对一操作:

<resultMap id="orderMap" type="order">
    <result property="id" column="id"></result>
    <result property="ordertime" column="ordertime"></result>
    <result property="total" column="total"></result>
    <!-- 
   		当查询order的时候,mybatis会把查询结果中的uid列中的数据,一个一个拿出来,然后调用				UserMapper.findById方法,查询数据,并把查询到数据,封装到order对象的user属性中。
    -->
    <association property="user" javaType="user"
                 select="com.ittest.dao.UserMapper.findById" column="uid">
    </association>
</resultMap>

<!-- 获取所有的order -->
<select id="findAll" resultMap="orderMap">
    SELECT * FROM orders
</select>

<!-- 根据用户id,查询对应的所有的订单 -->
<select id="findByUid" resultType="order">
    SELECT * FROM orders WHERE uid = #{uid}
</select>

2. 对多操作:

<resultMap id="userMap" type="user">
    <result property="id" column="id"></result>
    <result property="username" column="username"></result>
    <result property="password" column="password"></result>
    <result property="birthday" column="birthday"></result>

    <!-- 
   		当查询user的时候,mybatis会把查询结果中的id列中的数据,一个一个拿出来,然后调用					OrderMapper.findByUid方法,查询数据,并把查询到数据,封装到user对象的orders属性中。
   	-->
    <collection property="orders" ofType="order" 
                select="com.ittest.dao.OrderMapper.findByUid" column="id">	
    </collection>
</resultMap>

<!-- 获取所有用户 -->
<select id="findAll" resultMap="userMap">
        select * from user
</select>

<!-- 根据用户id,获取用户 -->
<select id="findById" resultType="user">
    select * from user where id = #{id}
</select>

3. 延迟加载

什么是延迟加载

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

什么是立即加载

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

<!-- 在SqlMapConfig文件中,开启mybatis的懒加载机制 -->
<settings>
    <setting name="lazyLoadingEnabled" value="true"/>
    <setting name="aggressiveLazyLoading" value="false"/>
</settings>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值