1.resultMap
select返回一个 HashMap 类型的对象,其中的键是列名,值便是结果行中的对应值
情况一:
必须提供一个无参数的构造函数
<resultMap id="getStudentRM" type="EStudnet">
<id property="id" column="ID"/>
<result property="studentName" column="Name"/>
<result property="studentAge" column="Age"/>
</resultMap>
id为主键,result为普通字段
情况二:
<resultMap id="getStudentRM" type="EStudnet">
<constructor>
<idArg column="ID" javaType="_long"/>
<arg column="Name" javaType="String"/>
<arg column="Age" javaType="_int"/>
</constructor>
</resultMap>
idArg为主键,arg为普通字段
2.resultMap和resultType的区别
resultType用于字段名和属性名相同的情况,或jdk已有数据类型,或在查询时使用
别名as
resultMap作用于字段名和属性名不一样时通过映射关系转换为属性值
3.嵌套查询和嵌套结果
以association(一对一)为例
查询:
<resultMap id="blogResult" type="Blog">
<!-- 此处column作为参数传递给selectAuthor -->
<association property="author"
column="author_id" javaType="Author" select="
selectAuthor"/>
</resultMap>
<select id="
selectAuthor" resultType="Author">
SELECT * FROM AUTHOR WHERE ID = #{
id}
</select>
结果:
<select id="selectBlog" resultMap="
blogResult">
select
B.id as blog_id,
B.title as blog_title,
B.author_id as blog_author_id,
A.id as author_id,
A.username as author_username,
A.password as author_password,
A.email as author_email,
A.bio as author_bio
from Blog B left outer join Author A on B.author_id = A.id
where B.id = #{id}
</select>
<!--
情况一,
authorResult可重用 -->
<resultMap id="
blogResult" type="Blog">
<id property="id" column="blog_id" />
<result property="title" column="blog_title"/>
<
association property="author" column="blog_author_id" javaType="Author"
resultMap="
authorResult"/>
</resultMap>
<resultMap id="
authorResult" type="Author">
<id property="id" column="author_id"/>
<result property="username" column="author_username"/>
<result property="password" column="author_password"/>
<result property="email" column="author_email"/>
<result property="bio" column="author_bio"/>
</resultMap>
<!--
情况二,authorResult不可重用 -->
<resultMap id="
blogResult" type="Blog">
<id property="id" column="blog_id" />
<result property="title" column="blog_title"/>
<
association property="author" javaType="Author">
<id property="id" column="author_id"/>
<result property="username" column="author_username"/>
<result property="password" column="author_password"/>
<result property="email" column="author_email"/>
<result property="bio" column="author_bio"/>
</association>
</resultMap>
4.collection(一对多)
<select id="selectBlog" 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中ofType类似association中的javaType -->
<
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>