Mybatis Plus 查询嵌套子列表 两种方式:集中查询;分布查询

本文介绍了使用Mybatis Plus进行嵌套子列表查询的两种方式,包括集中查询和分布查询。集中查询适用于不复杂的场景,而分布查询则提供更大的灵活性,尤其在对子查询有复杂需求时,如排序或处理字段名冲突。

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

Mybatis Plus 查询嵌套子列表 两种方式:集中查询;分布查询。

要得到类似结果结构如下:
Array(2)
	0: {
        id: '',
        list: Array(8)
            0: {…}
            1: {…}
            2: {…}
            3: {…}
            4: {…}
            5: {…}
            6: {…}
            7: {…}
	}
	1: {…}
  1. 方式一 collection分步查询:相对灵活自由(例如,对子查询有更复杂的查询可选用此方式)

// 主表查询dao.java
List<dto> selectAll(@Param(Constants.WRAPPER)QueryWrapper<Entity> wrapper);
//子表查询dao.java 
List<dto> getList(@Param(@Param("id" Long id));
<!-- 主表dao.xml-->
<resultMap type="com.*.dto.AllDTO" id="AllMap">
    <result property="id" column="id"/>
    <collection property="list" ofType="com.*.Entity"
                select="dao.getList"  column="id"><!-- 主表colum的id 传递给子表查询-->
    </collection>
</resultMap>
<select id="selectAll" resultMap="AllMap">
	select * from demo ${ew.customSqlSegment}
</select>
<!-- 子表dao.xml-->
<select id="getList" resultType="com.*.Entity">
    select * from other where demo_id=#{id} order by id asc
</select>

推荐方式一。可避免两个表中字段名重复,导致QueryWrapper的查询参数配置找不到column。对子表有更复杂的查询操作时,会更灵活,比如说排序等。

  1. 方式二 集中查询:对于不复杂的查询,写起来更快捷简单

// 主表查询dao.java
List<dto> selectAll(@Param(Constants.WRAPPER)QueryWrapper<Entity> wrapper);
<!-- 主表dao.xml-->
<resultMap type="com.*.AllDTO" id="AllMap">
    <result property="id" column="id"/>
    <result property="arrange" column="arrange"/>
    <collection property="list" ofType="com.*.DTO">
        <result column="id" property="id" />
        <result column="name" property="name" />
        <result column="type" property="type" />
    </collection>
</resultMap>

<select id="selectAll" resultMap="AllMap">
	select demo.*,other.id,other.name,other,type
    from demo left join other on demo.id = other.demo_id
    ${ew.customSqlSegment}
</select>

er on demo.id = other.demo_id
${ew.customSqlSegment}


> 两种方式各有利弊,在此纪录一下!
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值