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>

问题是,我必须在我的 Element 对象中进行集合。两个集合都包含属性。区别在于属性的类型(映射到 a_type)。根据这种类型,我喜欢在集合 1 或集合 2 中使用属性。我玩弄了鉴别器,但并不真正理解我在做什么,它不起作用......

这是想法,但是如何根据 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>

提前致谢

4

1 回答 1

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 放入集合中,那就更好了。

也许是一个愚蠢的建议,但谁知道呢?也许暗示不同的方法?[哦,除了显而易见的:创建两个查询]

于 2012-05-23T20:52:59.780 回答