Mybatis How to map a column from another table to

2019-08-19 12:28发布

问题:

I have a table t_comment, and a table t_comment_photo.

t_comment has column id, content; t_comment_photo has column id, comment_id, photo_url. t_comment_pohto contains the url of comment photos, a comment can have 0 to many comment photos.

These are their java classes:

public class ToyComment {
    private Integer id;
    private String content;
    private List<String> urls;
    ...
}
public class CommentPhoto {
    private Integer id;
    private String commentId;
    private String comment_url;
    ...
}

Here is the <select> content in mapper:

<select id="getToyCommentList"
    resultType="com.domain.ToyComment">
    c.id, c.content,p.user_photo_url userPhoto
    from t_comment c left join t_comment_photo p
    on c.id = p.comment_id
</select>

When I try to map the userPhoto queried from table t_comment_photo to a element of the list inside the java class ToyComment, I am getting errors.

The resultMap I am trying to fix is:

<resultMap id="ToyCommentResultMap" type="com.domain.ToyComment">
        <result column="id" jdbcType="VARCHAR" property="id" />
        <result column="content" jdbcType="VARCHAR" property="content" />
        <!-- <result property="urls"  jdbcType="VARCHAR" javaType="java.util.ArrayList" column="userPhoto" /> -->
        <collection property="urls" javaType="list" jdbcType="VARCHAR"  column="userPhoto"></collection>
    </resultMap> 

I tried both <property> and <collection>, but neither are working.

When I used <collection>, I got "Mapped Statements collection already contains value for com.toy.mapper.ToyCommentMapper.getToyCommentListByToyId" error, when I used <result>, I got "No typehandler found for property userPhotos". Use "java.util.ArrayList" or "list" for javaType doesn't change the output error.

I tried to search for "mybatis map to string list", but most are about mapping to a list of objects.

How to fix it right?

回答1:

The result map should look as follows:

<resultMap id="ToyCommentResultMap" type="com.domain.ToyComment">
  <id column="id" property="id" />
  <result column="content" property="content" />
  <collection property="urls" javaType="list"
    ofType="string">
    <result column="userPhoto" />
  </collection>
</resultMap>

A few notes:

  • Specify <id /> when using <collection />. It improves efficiency and is required in some cases.
  • In <select />, you need to specify resultMap instead of resultType (obviously).
  • This is a tricky case and we have added an FAQ entry just recently.