2012-05-23 54 views
0

這是MyBatis的XML配置的一部分。取決於列值的不同集合

<sql id="selectElementWithAttributes"> 
    SELECT 
    e.id as id, 
    e.title as title, 
    e.type as type, 
    e.date as date, 
    e.ownerid as ownerid, 
    a.attributeid as attributeid, 
    a.value as value, 
    a.type as a_type 
    FROM 
    test_element as a 
    LEFT JOIN 
    test_elementattributes as a 
    ON 
    e.id 
    = a.parentid 
</sql> 

現在我使用resultMap將列映射到我的對象。

<resultMap type="Element" id="rmElement"> 
    <id property="id" column="id" /> 
    <result property="title" column="title" /> 
    <result property="type" column="type" /> 
    <result property="date" column="date" /> 
    <result property="ownerid" column="ownerid" /> 
    <collection property="attributes" ofType="Attribute"> 
     <id property="{id=parentid,attributeid=attributeid}" /> 
     <result property="key" column="attributeid" /> 
     <result property="value" column="value" /> 
    </collection> 
</resultMap> 

問題是,我有我的元素對象的集合。 這兩個集合都包含屬性。 不同之處在於屬性的類型(映射到a_type)。 取決於這種類型,我喜歡在集合1或集合2中具有屬性。 我用鑑別器玩弄,但並不真正瞭解我在做什麼,它不工作...

This是這個想法,但是如何根據a_type切換集合?

<resultMap type="Element" id="rmElement"> 
    <id property="id" column="id" /> 
    <result property="title" column="title" /> 
    <result property="type" column="type" /> 
    <result property="date" column="date" /> 
    <result property="ownerid" column="ownerid" /> 
    <collection property="attributes" ofType="Attribute"> 
     <id property="{id=parentid,attributeid=attributeid}" /> 
     <result property="key" column="attributeid" /> 
     <result property="value" column="value" /> 
    </collection> 
    <collection property="attributesOther" ofType="Attribute"> 
     <id property="{id=parentid,attributeid=attributeid}" /> 
     <result property="key" column="attributeid" /> 
     <result property="value" column="value" /> 
    </collection> 
</resultMap> 

在此先感謝

回答

1

沒用過這玩意,所以只是一個想法。修改查詢以返回兩組屬性,然後在讀取結束時過濾出NULL值?

<sql id="selectElementWithAttributes"> 
    SELECT 
    e.id as id, 
    e.title as title, 
    e.type as type, 
    e.date as date, 
    e.ownerid as ownerid, 
    CASE WHEN a.type = 'attribute1' THEN a.attributeid ELSE NULL END as attribute1id, 
    CASE WHEN a.type = 'attribute2' THEN a.attributeid ELSE NULL END as attribute2id, 
    a.value as value, 
    a.type as a_type 
    FROM 
    test_element as a 
    LEFT JOIN 
    test_elementattributes as a 
    ON 
    e.id 
    = a.parentid 
</sql> 

然後將兩個不同的集合放在屬性1和屬性2的結果圖中。兩個集合都將獲得完整集合,但對於不屬於該集合的屬性,這些值將爲NULL。或者如果NULL是合法值,則使用不同的標誌。更好的是,如果有一種方法可以跳過將NULL放入集合中。

也許一個愚蠢的建議,但誰知道?也許暗示了一種不同的方法? [哦,和其他明顯的:創建兩個查詢]

+0

完美的作品。我需要處理這兩個集合,但速度夠快。非常感謝 – Nabor