Wednesday, September 12, 2007

Chaining selects in iBatis

If you ever have to chain two selects because the Objects are related, there is some info about it on page 32 of iBatis user guide. I created a fully functional example to demonstrate how it is done. In the following example when we run Info, we will also have Address information for that person even though they are separate SqlMaps containing separate resultMaps

EXAMPLE
-------
Person.xml
---------
<sqlMap namespace="Person">

< id="infoMap" class="Details">
< property="PersonId" column="Id" javatype="java.lang.Long">
< property="PersonName" column="Name" javatype="java.lang.String">
< property="PersonAge" column="Age" javatype="java.lang.Long">
< property="PersonGender" column="Gender" javatype="java.lang.String">
< property="Address" column="Id" javatype="Address" select="Address.getAddressById">

< /resultMap>

< id="loadInfo" parameterclass="java.lang.Long" resultmap="infoMap">

SELECT Id, Name, Age, Gender
FROM Person
WHERE ssn = #value#

< /select>

1.Pass value of column specified in cloumn to select id 'getAddressById' in SqlMap with name space Address (contains address related queries)
javatype="Address" is a reslut bean for getAddressById containing fields Street, City, State and ZIP

Address.xml
-----------
<sqlMap namespace="Address">

< id="Address" class="Address">
< property="PersonStreet" column="Street" javatype="java.lang.String">
< property="PersonCity" column="City" javatype="java.lang.String">
< property="PersonState" column="State" javatype="java.lang.String">
< property="PersonZIP" column="ZIP" javatype="java.lang.Long">
< /resultMap>

< id="getAddressById" parameterclass="java.lang.Long" resultmap="Address">

SELECT Street, City, State, ZIP
FROM Address
WHERE id = #value#

< /select>

So, when you run infoMap above you will also have address details for that person.

No comments: