[英]How to implement one-to-many relationships in Ibatis?
假設我有這個類:
Class A {
int id;
int[] b;
// Other properties
}
Class B {
int id;
// Other properties
}
A 類與 B 類具有一對多關系。我已經有一個服務可以緩存 B 對象並在 id 上返回它們。
表架構看起來像這樣
Table a:
-------
int id,
prop1,
etc
Table a_to_b_map
----------------
int a_id,
int b_id
現在,我如何在 iBatis 中映射它?
由於 B 對象已被緩存,因此我想將 id 列表放入 A 對象中,然后使用該服務來豐富 As。
有人可以建議如何去做嗎?
我能想到的兩種可能的選擇是:
好吧,我可以在http://svn.apache.org/repos/asf/ibatis/trunk/java/ibatis-2/ibatis-2-docs/en/iBATIS-SqlMaps-的 iBatis 2開發者文檔中找到一些有用的信息。 2_en.pdf (具體而言,第36,37頁)
在 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
不確定我是否正確理解了您的問題。
假設您將根據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'的對象
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.