【问题标题】:Return Multiple Types from a Single ibatis Query从单个 ibatis 查询返回多种类型
【发布时间】:2014-03-18 20:41:46
【问题描述】:

我有一个搜索表单,需要包含来自两个不同表的结果。这些表彼此没有关系,也没有我们分开的关系。在我的示例场景中,我们有加油站和杂货店。杂货店表可能具有诸如 freezerSize、produceStorage、numberOfCarts 之类的属性。加油站表可能有 gasTankSizeInGallons、windowCleanerInGallons 等......这两个表之间有一些共享字段(即 - numberOfEmployees、squareFeetOfStoreSpace、numberOfShelves 等......)。

我的搜索查询需要将加油站和杂货店一起排序和显示。我正在考虑使用 SQL 联合并将不适用的字段设置为 0 或 null。但是,我真的很困惑如何使用 ibatis 来做到这一点(因为这两个对象属于不同的类型):

<select id="searchQuery" parameterClass="java.util.Map" resultClass="????????????????">
    SELECT
        storeName, storeCity, storeState, numberOfCarts, freezerSize, 0 gasTankSizeInGallons, 0 windowCleanerInGallons
    FROM
        grocery_stores
    UNION
    SELECT
        storeName, storeCity, storeState, 0 numberOfCarts, 0 freezerSize, gasTankSizeInGallons, windowCleanerInGallons
    FROM
        gas_stations
    ORDER BY storeState, storeCity, storeName
</select>

注意 - 实际查询的顺序有很多,它是分页的,并且选择中还有更多字段(加上选择字段中每个适用字段的 where 子句)。

上述查询的 resultClass 应该是什么?我有一个 GroceryStore 和 GasStation 类,它们都从 Store 扩展而来。但是,Store 没有很多 GroceryStore 和 GasStation 特定字段。我可以做两个单独的查询,但是结果的排序必须在 java 中完成,而且效率很低,因为它需要先加载大量数据。

谢谢

【问题讨论】:

    标签: java mysql ibatis


    【解决方案1】:

    经过多次谷歌搜索,我找到了自己问题的答案。

    ibatis 鉴别器将在 gasStation 和groceryStore 类之间进行选择。

    <resultMap id="searchResultMap" class="Store">
         <discriminator column="storeType" javaType="java.lang.String">
               <subMap value="grocery" resultMap="groceryStoreMap"/>
               <subMap value="gasStation" resultMap="gasStationMap"/>
         </discriminator>
    </resultMap>
    

    然后我将编辑我的查询以在选择字段中添加 storeType 并为groceryStore 和gasStation 创建一个resultMap。

    注意 - 为了弄清楚这一点,我阅读了this stackoverflow question

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-09-09
      • 2021-04-13
      • 2020-05-27
      • 2020-12-14
      • 2018-09-14
      • 2023-01-28
      相关资源
      最近更新 更多