以下是我的 mapper 文件的内容,是一个一对多查询。但是查询结果的 Book 映射不是一个,并且不能映射正确。
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.bookstore.mapper.BookMapper">
<resultMap id="resultOfQueryBookById" type="Book" autoMapping="true">
<collection property="tags" ofType="BookTag" columnPrefix="bt_" autoMapping="true"/>
<collection property="authors" ofType="BookAuthor" columnPrefix="ba_" autoMapping="true"/>
<collection property="comments" ofType="BookComment" columnPrefix="bc_" autoMapping="true"/>
<collection property="previews" ofType="BookPreview" columnPrefix="bp_" autoMapping="true"/>
</resultMap>
<select id="queryBookById" resultMap="resultOfQueryBookById">
SELECT b.*,
bc.id bc_id,
bc.content bc_content,
bc.digg bc_digg,
bc.bury bc_bury,
bc.type bc_type,
bc.post_date bc_post_date,
bt.tag bt_tag,
ba.author ba_author,
bp.url bp_url
FROM books b
INNER JOIN book_tags bt ON bt.book_id = b.id
INNER JOIN book_authors ba ON ba.book_id = b.id
INNER JOIN book_comments bc ON bc.book_id = b.id
INNER JOIN book_previews bp ON bp.book_id = b.id
WHERE b.id = #{id};
</select>
</mapper>
我开启了 resultMap 自动映射,所以 collection 和 resultMap 第一层都没有任何子标签。但问题就出在这里,就是因为我的主表,即 Book 没有手动添加 id 的 result 子标签导致查询结果不能正确映射。
因此,在开启自动映射的情况下,有一对多或者多对一,主表的实体类 Book 必须包含一个 id 字段(主键)的 result 子标签。
<resultMap id="resultOfQueryBookById" type="Book" autoMapping="true">
<result property="id" column="id"/>
<collection property="tags" ofType="BookTag" columnPrefix="bt_" autoMapping="true"/>
<collection property="authors" ofType="BookAuthor" columnPrefix="ba_" autoMapping="true"/>
<collection property="comments" ofType="BookComment" columnPrefix="bc_" autoMapping="true"/>
<collection property="previews" ofType="BookPreview" columnPrefix="bp_" autoMapping="true"/>
</resultMap>