Let's say I have this Class:
Class A {
int id;
int[] b;
// Other properties
}
Class B {
int id;
// Other properties
}
The Class A has one-to-many relation with class B. I already have a service which caches B objects and return them on id.
Table schema looks something like this
Table a:
-------
int id,
prop1,
etc
Table a_to_b_map
----------------
int a_id,
int b_id
Now, how do I map this in iBatis?
Since, B objects are already cached, I want to get the list of ids into A objects and then use the service to enrich As.
Can someone suggest how to go about it?
Two possible alternative I can think of are:
in mybatis 3 it's little bit different. You can do it by specify two select statement or you can use join then create resultMap with collection tag.
<resultMap id=”blogResult” type=”Blog”>
<collection property="posts" javaType=”ArrayList” column="blog_id"
ofType="Post" select=”selectPostsForBlog”/>
</resultMap>
<select id=”selectBlog” parameterType=”int” resultMap=”blogResult”>
SELECT * FROM BLOG WHERE ID = #{id}
</select>
<select id=”selectPostsForBlog” parameterType=”int” resultType="Author">
SELECT * FROM POST WHERE BLOG_ID = #{id}
</select>
or you can use join
<select id="selectBlog" parameterType="int" resultMap="blogResult">
select
B.id as blog_id,
B.title as blog_title,
B.author_id as blog_author_id,
P.id as post_id,
P.subject as post_subject,
P.body as post_body,
from Blog B
left outer join Post P on B.id = P.blog_id
where B.id = #{id}
</select>
and do result map
<resultMap id="blogResult" type="Blog">
<id property=”id” column="blog_id" />
<result property="title" column="blog_title"/>
<collection property="posts" ofType="Post">
<id property="id" column="post_id"/>
<result property="subject" column="post_subject"/>
<result property="body" column="post_body"/>
</collection>
</resultMap>
you can get complete totorial from ibatis user guide here :
http://svn.apache.org/repos/asf/ibatis/java/ibatis-3/trunk/doc/en/iBATIS-3-User-Guide.pdf
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With