one to many relation using mybatis or ibatis

2020-03-06 18:34发布

问题:

I have database which has two tables

  post: 
    id
    post_name
    post_desc        

  files:
    file_id
    file_name

  post_attachments
    post_id
    file_id

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>

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.

I have my PostBean like

public class PostBean extends Post {

 private List<FileAttachment> filesAttachment;
 //getter setter
}

I am using mybatis with spring and mysql as database Please let me know if you need anything else.

--update--

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>    

回答1:

As shown in the manual, you have to write a more complex query and change the mapper.

The request will be something like that :

<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>

And your result map :

<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>