Wednesday, July 28, 2010

Nested iBatis Result Mappings

Although, this is not an earth shattering iBatis discovery, it is a time saver, both in development and maintenance so thought I would share it.

Let's assume we have a class called CompanyType that contains type_id and type name and another class called Company that among other properties has a CompanyType object companyType included.

In the iBatis xml file the result map for CompanyType would look something like

<sqlMap namespace="CompanyType">
<resultMap id="companyTypeResultMap" class="com.sample.CompanyType">
<result column="company_type_id" property="typeId"/>
<result column="company_type_nm" property="typeName"/>
</resultMap>
...

In the ibatis xml file for Company the result map would look like:

<sqlMap namespace="Company">
<resultMap id="companyResultMap" class="com.sample.Company">
<!-- other company properties here -->
<result column="company_type_id" property="companyType.typeId"/>
<result column="company_type_nm" property="companyType.typeName"/>
</resultMap>


The problem with this is that if something changes in company type, you have to know to change it in two locations. Makes it harder to maintain. Instead though you could do the following:

<sqlMap namespace="Company">
<resultMap id="companyResultMap" class="com.sample.Company">
<!-- other company properties here -->
<result property="companyType" resultMap="CompanyType.companyTypeResultMap"/>
</resultMap>


As you can see, now if the result map is updated in CompanyType, the changes are automatically reflected in the Company ibatis file. Hope you find this helpful. I know I did.

1 comment:

Neo Parks said...

I have a couple of nested ResultMaps in iBatis that have exactly same database column names. This is causing ambiguity and resulting in incorrect result being retrieved for the different database tables.

For e.g.,`














`
Now when I write my select query joining the Size & Consignment tables, I get the same values for Shipment Code and Shipment Unit returned, whereas there are different values for these two columns in the database.

Could you help me solve this problem?