Saturday, February 12, 2011

Reusing a resultMap for different column names

Is there a way of reusing the same resultMap multiple times in a single query.

For example, suppose I have a "foo" resultMap:

<resultMap id="foo" class="Foo">
  <result property="Bar" column="bar" />
</resultMap>

Is there a way to define another resultMap that reuses the above for different columns? Something like...

<resultMap id="fizz"class="Fizz">
  <result property="Foo1" column="bar=bar1" resultMapping="foo" />
  <result property="Foo2" column="bar=bar2" resultMapping="foo" />
  <result property="Foo3" column="bar=bar3" resultMapping="foo" />
</resultMap>
  • Almost. If you select the ID of the Foo in your query, you can have the Fizz result map execute a SELECT for that ID, which will use the Foo result map.

    <result property="Foo1" column="bar1Id" select="selectFoo"/>

    (Assuming you have a selectFoo query defined.) But that's extremely slow with large result sets, since it does an additional SELECT for every row.

    iBATIS has a solution to this problem for the typical case, where you have a composite object that contains various other objects. First, you define a query that joins your tables, then you can use fooMap to populate a Foo:

    <result property="Foo1" resultMap="fooMap"/>

    But you can't use that result map twice for two different Foos because the result map specifies certain column names. You can use another technique, though:

    <result property="foo1.bar" column="foo1bar"/>
    <result property="foo2.bar" column="foo2bar"/>

    More detail in page 35 of the iBatis Datamapper manual.

    Andrew : That's unfortunate. In my case, the resultMap I'd like to reuse is rather simple and I've only hit this in one query, so I'll keep it simple and just *gasp* copy-paste for now.
    From James Rose

0 comments:

Post a Comment