假设我有这个班级:
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。
有人可以建议如何去做吗?
我能想到的两种可能的选择是:
答案 0 :(得分:2)
好吧,我可以在http://svn.apache.org/repos/asf/ibatis/trunk/java/ibatis-2/ibatis-2-docs/en/iBATIS-SqlMaps-2_en.pdf的iBatis 2开发者文档中找到一些有用的信息(具体来说,第36,37页)
答案 1 :(得分:1)
在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>
或者您可以使用加入
<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
答案 2 :(得分: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”
对象