MyBatis 实现一对多有几种方式,怎么操作的?

本文介绍了MyBatis中实现一对多关联查询的三种常见方法:嵌套查询、嵌套结果映射以及使用Association和Collection标签。通过示例展示了如何在不同场景下选择合适的查询方式。

        MyBatis 实现一对多关联查询通常有以下几种方式:

1. 嵌套查询(Nested Queries):

        这种方式通过在主查询中嵌套子查询,实现一对多的关联查询。比如,在父对象(一)的查询语句中嵌套子对象(多)的查询语句,通过外键关联父子对象。

示例:

<select id="selectParentWithChildren" resultMap="parentResultMap">
    SELECT parent.id as parent_id, parent.name as parent_name,
           child.id as child_id, child.info as child_info
    FROM parent_table parent
    LEFT JOIN child_table child ON parent.id = child.parent_id
</select>

2. 嵌套结果映射(Nested Result Maps):

        这种方式通过定义多个结果映射,让 MyBatis 在执行查询时,自动将多个结果集映射到对象的嵌套属性中。

示例:

<!-- 定义父对象的映射 -->
<resultMap id="parentResultMap" type="ParentEntity">
    <id property="id" column="parent_id"/>
    <result property="name" column="parent_name"/>
    <!-- 嵌套子对象的映射 -->
    <collection property="children" ofType="ChildEntity">
        <id property="id" column="child_id"/>
        <result property="info" column="child_info"/>
    </collection>
</resultMap>

<!-- SQL 查询语句 -->
<select id="selectParentWithChildren" resultMap="parentResultMap">
    SELECT parent.id as parent_id, parent.name as parent_name,
           child.id as child_id, child.info as child_info
    FROM parent_table parent
    LEFT JOIN child_table child ON parent.id = child.parent_id
</select>

3. 使用 MyBatis 的一对多关联映射(Association 和 Collection):

        可以通过 MyBatis 的 <association><collection> 标签,显式定义父子对象之间的关联关系和映射。

示例:

<select id="selectParentWithChildren" resultMap="parentResultMap">
    SELECT parent.id as parent_id, parent.name as parent_name,
           child.id as child_id, child.info as child_info
    FROM parent_table parent
    LEFT JOIN child_table child ON parent.id = child.parent_id
</select>

<resultMap id="parentResultMap" type="ParentEntity">
    <id property="id" column="parent_id"/>
    <result property="name" column="parent_name"/>
    <!-- 使用 <collection> 定义一对多关联映射 -->
    <collection property="children" ofType="ChildEntity" select="selectChildrenByParentId">
        <id property="id" column="child_id"/>
        <result property="info" column="child_info"/>
    </collection>
</resultMap>

<select id="selectChildrenByParentId" parameterType="long" resultType="ChildEntity">
    SELECT id, info
    FROM child_table
    WHERE parent_id = #{id}
</select>

        以上是常用的几种方式,根据具体业务需求和数据结构的复杂度,选择合适的方式来实现一对多的关联查询。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

NZC2237

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值