首页 > 解决方案 > 在 Mybatis 的嵌套集合中再次使用相同的结果集

问题描述

我有以下 Mybatis resultMap,在一个集合中有一个集合:

<resultMap id="getAllDeliveries" type="foo.bar.dao.pojo.Delivery">
    <id property="id" column="deliveryId" />
    // some more stuff
    <collection property="topicGroups" resultSet="topics-1" resultMap="topicGroups" 
            column="deliveryId" foreignColumn="deliveryId"
            ofType="foo.bar.dao.pojo.TopicGroup" />
</resultMap>

<resultMap id="topicGroups" 
        type="foo.bar.dao.pojo.TopicGroup"
        autoMapping="true">
    <id property="id" column="topicGroupId" />
    <collection property="dataTopics" resultSet="topics-2"
            column="deliveryId" foreignColumn="deliveryId"
            ofType="foo.bar.dao.pojo.DataTopic">
        <result property="id" column="topicId" />
        // some more stuff
    </collection>
</resultMap>

使用以下 SQL 查询,该查询由主查询和 2 次完全相同的次要查询组成:

<select id="getAllDeliveries" 
    resultSets="deliveries,topics-1,topics-2"
    resultMap="getAllDeliveries">

    SELECT delivery.[deliveryId]
            <!-- some more stuff -->
    FROM [Delivery] as delivery
    
    SELECT dtglink.deliveryId,
        dtglink.topicGroupId,
        tgSet.topicId
    FROM [DeliveryTopicGroup] dtglink
    INNER JOIN [DatasetTopicGroupSet] as tgSet
        ON dtglink.topicGroupId = tgSet.topicGroupId;
        
    SELECT dtglink.deliveryId,
        dtglink.topicGroupId,
        tgSet.topicId
    FROM [DeliveryTopicGroup] dtglink
    INNER JOIN [DatasetTopicGroupSet] as tgSet
        ON dtglink.topicGroupId = tgSet.topicGroupId;

</select>

如果不执行两次相同的查询,我无法获得相同的结果。我尝试在内部集合中再次使用相同的 resultSet,并尝试从内部集合中省略 resultSet 属性,但在这两种情况下,整个 topicGroups 属性都是 NULL。

有没有办法在 resultMap 中执行此操作而无需执行两次相同的查询?(我也不想为此使用 TypeHandler。)

标签: javamybatis

解决方案


推荐阅读