问题描述
我有两个表的数据库
post:
id
post_name
post_desc
files:
file_id
file_name
post_attachments
post_id
file_id
在我的xml映射中,我已经有了
In my xml mapping I already have
<select id="selectPosts" resultType="com.mycom.myproject.bean.postBean">
select id, post_name as postName from post
</select>
因此,这是一对多的关系.我希望将所有文件附加到帖子中.我不知道如何在mybatis中进行映射.
So its a one to many realtionship. I want all the files attached to a post. I don't understand how I can do the mapping in mybatis.
我有自己的PostBean,
I have my PostBean like
public class PostBean extends Post {
private List<FileAttachment> filesAttachment;
//getter setter
}
我将mybatis与spring和mysql作为数据库一起使用如果您还有其他需要,请告诉我.
I am using mybatis with spring and mysql as databasePlease let me know if you need anything else.
-更新-
我已将mapper.xml修改为
I have modified my mapper.xml as
<resultMap id="BaseResultMap" type="com.mycom.myproject.db.mybatis.model.post">
<!--
WARNING - @mbggenerated
This element is automatically generated by MyBatis Generator, do not modify.
This element was generated on Tue Sep 11 10:14:08 BST 2012.
-->
<id column="id" jdbcType="BIGINT" property="id" />
<result column="post_name" jdbcType="VARCHAR" property="postName" />
<collection property="filesAttachment" ofType="com.mycom.myproject.db.mybatis.model.FileAttachment">
<id property="fileId" column="file_id" />
<id property="fileName" column="file_name" />
</collection>
--- update2 ---
实际上我在上面也创建了一个映射表,所以查询就像
Actually I have one mapping table also which I have created above so my query is like
<select id="selectPosts" parameterType="string" resultType="com.mycom.myproject.bean.postBean">
select p.id, p.post_name, fa.file_id as fileId, fa.file_name as fileName from post p
left outer join files f on f.post_id = p.id join post_attachments pa on pa.file_id = f.post_id
where p.id = 371
</select>
推荐答案
如手册,您必须编写更复杂的查询并更改映射器.
As shown in the manual, you have to write a more complex query and change the mapper.
请求将是这样的:
<select id="selectPosts" resultType="com.mycom.myproject.bean.postBean">
select id, post_name, file_id, file_name as postName from post left outer join files
</select>
您的结果图:
<resultMap id="detailedPostResultMap" type="Blog">
<result property="id" column="id"/>
<result property="name" column="post_name"/>
<collection property=filesAttachment" ofType="FileAttachment">
<id property="fileId" column="file_id"/>
<result property="fileName" column="file_name"/>
</collection>
</resultMap>
这篇关于使用mybatis或ibatis一对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!