关于MybatisPlus嵌套结果

本文探讨了在MybatisPlus中如何处理嵌套结果查询,特别是在多表查询场景下。通常的单表操作已无法满足需求,因此需要自定义SQL来完成。举例说明了一段用于嵌套查询的SQL代码,并指出直接在主类中声明关联类变量可能导致数据冗余和大量Null值的问题。建议仅将需要的连表字段映射到主类的几个字段,以优化数据结构。

嵌套结果查询

多数时候我们都会涉及到多张表的查询,而mybatisPlus只是对单表的操作做了封装,而涉及到多表就有些无能为力,所以根据业务和需求我们就要自己封装写sql语句查询。比如以下的代码就是我自己根据需求写的一段sql,

 <!-- 通用查询映射结果 -->
<resultMap id="BaseResultMap" type="com.tsinghua.pes.domain.entity.AccountTenantCancel">
    <id column="auth_plan_id" property="authPlanId" />
    <result column="relation_tenant_id" property="relationTenantId" />
    <result column="data_cancel_time" property="dataCancelTime" />
    <result column="data_is_cutting_off_power" property="dataIsCuttingOffPower" />
    <result column="data_user_id" property="dataUserId" />
    <result column="data_add_time" property="dataAddTime" />
    <result column="data_content" property="dataContent" />
    <!--连接业主表的数据-->
    <result column="auth_tenant_id" property="authTenantId" />
    <result column="auth_tenant_name" property="authTenantName" />
    <result column="building_num" property="buildingNum" />
    <result column="tenant_num" property="tenantNum" />
</resultMap>
<select id="tenantCancelQueryPage" resultMap="BaseResultMap">
  select tenant.auth_tenant_id,tenant.auth_tenant_name,tenant.building_num,tenant.tenant_num,
  cancel.data_add_time,cancel.data_cancel_time,cancel.data_is_cutting_off_power
  from account_tenant_cancel cancel
  LEFT JOIN account_tenant tenant
  ON cancel.relation_tenant_id = tenant.auth_tenant_id
  ${ew.customSqlSegment}

</select>

通常我们会直接通过在类中直接声明有关联的一个类的类型的变量,但是这样有一个局限性就是主类的数据太冗余,很多字段我们的sql没有查询出来,但是因为添加的是一个对象所以该对象的字段都会是Null值,自身的字段和连表的字段都是Null,所以好的做法就是只添加我们需要连表的几个字段,把查询结果映射到这几个字段就好了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值