Mapping parent-child relationships with iBatis
- by agnul
I have the classic setup
public class Parent {
Integer id;
...
// No generics
Collection someCollectionAttribute;
...
public void setChildren(Collection c) {
...
}
}
public class Child {
Integer id;
...
}
and I'm trying to map this on the usual table setup using iBatis (version 2.30... don't ask).
create table parents (
ID integer primary key
...
)
create table children (
ID integer primary key
PARENT_ID integer references parents(id)
...
)
My mapping file looks like this
<resultMap id="ParentResult" groupBy="id">
<result property="id" column="ID" />
...
<result property="children" resultMap="ChildResult" />
</resultMap>
<resultMap id="ChildResult">
<result property="id" column="ID" />
<result property="parentId" column="PARENT_ID" />
...
</result>
<sql id="loadParent" resultMap="ParentResult">
select P.ID as p1, ..., C.ID as c1, C.PARENT_ID as c2 ...
from parents P
join children C on (P.ID = C.PARENT_ID)
where P.ID = #id#
order by P.ID
</sql>
Doing the usual sqlMap.queryForObject("loadParent", new Integer(42)) at first caused a NullPointerException inside the setChildren setter which apparently is called with a null argument (my bad). Fixing the setter everything works fine, but the logs show that setChildren is called only once before even running a single SQL statement, still with a null argument, so I'm wondering what's going on here. Anyone has any clues?