2009-02-04 24 views
5

比方說,我有這樣的類:如何在Ibatis中實現一對多關係?


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

    Class B { 
     int id; 
     // Other properties 
    } 

A類與B類一個一對多的關係,我已經有這緩存乙對象的一項服務,並返回他們的ID。

表的架構看起來像這樣


    Table a: 
    ------- 
     int id, 
     prop1, 
     etc 

    Table a_to_b_map 
    ---------------- 
     int a_id, 
     int b_id 

現在,我該如何在iBatis的地圖呢?

因爲B對象已經被緩存了,我想把ID列表變成A對象,然後使用該服務來豐富As。

有人可以建議如何去做?

兩個可能的選擇,我能想到的是:

  1. 創建A(ATOB地圖)的內部類,並使用SELECT查詢在iBatis的配置來填充這個
  2. 裏面的iBatis的結果映射/選擇使用另一個選擇以獲得B ID列表(不太確定如何在配置中執行此操作)

回答

0

不知道我是否正確理解了您的問題。

假設你將基於A的id進行查詢,那麼在ibatis中編寫一個連接兩個表的查詢呢?

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

然後,您可以使用'queryForMap'來返回a_id vs(查詢中記錄的集合)的散列表。使用自定義的方法來這個數據結構轉換爲「A」

+0

比ks Rahul。但是這種方法的問題是:「太多對象」,我們最終會在代碼中執行group_by(類似)。 – Jagmal 2009-02-04 08:13:28

1
在MyBatis的3

它有點不同。你可以通過指定兩個select語句來完成它,或者你可以使用join,然後使用collection標籤創建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> 

,或者您可以使用加入

<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的用戶指南在這裏得到完整的totorial:

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

相關問題