This is a part of my XML configuration for MyBatis.
<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>
now I use a resultMap to map the columns to my Object.
<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>
The problem is, I have to collections in my Element object.
Both Collections contain Attributes.
The difference is the type (mapped to a_type) of the attributes.
Depending on this type I like to have the Attribute in collection 1 or collection 2.
I played around with the discriminator, but don’t really understand what I was doing and it doesn’t work…
This is the idea, but how do I switch the collections depending on 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>
Thanks in advance
Never used this stuff, so just an idea. Modify the query to return two sets of attributes, then filter out the NULLs on the reading end?
Then put your two different collections in the resultmap for attribute1 and attribute2. Both collections will get the full set, but the values will be NULL for the attributes that don’t belong to the set. Or use a different flag if NULL is a legit value. Even better if there is a way to skip putting NULLs into the collection.
Maybe a silly suggestion, but who knows? Perhaps a hint to a different approach?
[Oh, and other than the obvious: create two queries]