Java 如何在Ibatis中实现一对多关系?
假设我有一门课:Java 如何在Ibatis中实现一对多关系?,java,ibatis,one-to-many,Java,Ibatis,One To Many,假设我有一门课: Class A { int id; int[] b; // Other properties } Class B { int id; // Other properties } 类A与类B有一对多关系。我已经有了一个缓存B对象并在id上返回它们的服务 表架构看起来像这样 Table a: ------- int id,
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
有人能建议怎么做吗
我能想到的两种可能的选择是:
在AtoB映射中创建一个内部类,并使用iBatis配置中的select查询来填充该类
在iBatis resultMap/select中,使用另一个select来获取B ID列表,但不太确定如何在配置中执行此操作
不确定我是否正确理解了你的问题 假设您将基于A的id进行查询,那么在ibatis中编写一个连接两个表的查询如何
select *
from a, a_to_b_map
where a.id = #id# and a.id = a_to_b_map.a_id
然后,您可以使用“queryForMap”从查询中返回一个\u id与记录集合的哈希映射。使用自定义方法将此数据结构转换为mybatis 3中的“a”对象,这有点不同。您可以通过指定两个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用户指南中获取完整的totorial:
谢谢拉胡尔。但这种方法的问题是:对象太多,我们最终会在代码中使用类似的方法来进行组_。好吧,我可以在iBatis 2开发人员文档中找到一些有用的信息,与Jagmal发布的文档相同,可能不太容易链接: