How to implement a one-to-many relationship in Ibatis?

Say I have this class:


    Class A {
        int id;
        int[] b;
        // Other properties
    }

    Class B {
        int id;
        // Other properties
    }

Class A has a one-to-many relationship with class B. I already have a service that caches objects B and returns them to id.

The table layout 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 display this in iBatis?

Since B objects are already cached, I want to get a list of identifiers in A-objects, and then use the service to enrich As.

Can anyone suggest how to do this?

There are two possible alternatives:

  • Create an inner class in (AtoB map) and use the select query in the iBatis configuration to populate this
  • Inside iBatis resultMap / select, use another choice to get a list of B identifiers (not too sure how to do this in the configuration)
+5
3

mybatis 3 . , select, join, resultMap .

<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>

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>

<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>

ibatis:

http://svn.apache.org/repos/asf/ibatis/java/ibatis-3/trunk/doc/en/iBATIS-3-User-Guide.pdf

+1

, .

, A id, ibatis, ?

select * 
from a, a_to_b_map 
where a.id = #id# and a.id = a_to_b_map.a_id

Then you can use 'queryForMap' to return hashmap a_id vs (collecting records from the query). Use a special method to convert this data structure to object "A"

0
source

All Articles