目录
一、对象不同
1. resultMap
2. resultType
3. 分析
二、描述不同
1、resultMap
2、resulTtype
三、类型适用不同
一、对象不同
1. resultMap
如果查询出来的结果的列名和实体属性不一致,通过定义一个resultMap对列名和pojo属性名之间作一个映射关系(示例代码如下)。
<!--结果返回类型采用resultMap定义-->
<select id="findCardById" parameterType="int" resultMap="findCard">select * from card where id=#{id}
</select><!--对上述resultMap进行自定义映射-->
<resultMap id="findCard" type="card"><id property="id" column="id"/><result property="number" column="number"/>
</resultMap>
2. resultType
resultType使用resultType进行输出映射,只有查询结果显示的列名和实体的属性名一致时,该列才可以映射成功。
<!--结果返回类型采用resultType定义-->
<select id="findCardById" parameterType="int" resultType="card">select * from card where id=#{id}
</select>
3. 分析
从上述的实例代码可以看出,针对相同的类的映射,resultType和resultMap均可实现。
- 对于resultMap而言,除了需要在<select>标签中进行申明外,还需要单独使用<resultMap></resultMap>实现实体属性与数据库表列名之间的自定义映射,适合多表查询。
- 对于resultType而言,仅需在<select>标签中用resultType属性申明结果返回类型即可,适合单表查询。
二、描述不同
1、resultMap
对于一对一表连接的处理方式通常为在主表A的实体中添加嵌套另一个表B的实体,然后在mapper.xml中采用<association>元素进行对另一个表B的连接处理,其中<association>元素中的select的值为表B对应的SQL语句的唯一标识,一般为namespace+SQL语句的id。
在下述例子中,person实体与card实体是一对一的关系,查询要求是:根据person表中id的值查询用户的id,name,age,sex以及卡号number,但是在person表中只有number对应的card表的id值,故需要采用resulMap。
1.1 Cad类
package com.chen.pojo;
public class Card {private int id;private String number;//toString方法、set以及get方法省略
}
1.2 Cad类对应数据库表
1.3 Cad类对应映射文件
<mapper namespace="com.chen.mapper.CardMapper" ><select id="findCardById" parameterType="int" resultMap="findCard">select * from card where id=#{id}</select><resultMap id="findCard" type="card"><id property="id" column="id"/><result property="number" column="number"/></resultMap>
</mapper>
1.4 Person类
package com.chen.pojo;
public class Person {private int id;private String name;private int age;private String sex;//toString方法、set以及get方法省略
}
1.5 Person类应数据库表
1.6 Person类对应映射文件
<select id="findPersonById"parameterType="Integer"resultMap="CardWithPerson">select * from person where id=#{id}</select><!--自定义结果集映射,对上述resultMap进行映射处理--><resultMap id="CardWithPerson" type="person"><id property="id" column="id"/><result property="name" column="name"/><result property="sex" column="sex"/><result property="age" column="age"/><!--使用association实现一对一映射property为实体属性javaType为该实体属性的类型select指向SQL语句值为对应语句的唯一标识,由于该参数来自上一条语句的及如果,所以值为即namespace+idcolumn为所需属性对应在库表中的列名--><association property="cardnumber" javaType="Card" column="card_id"select="com.chen.mapper.CardMapper.findCardById"/></resultMap>
2、resulTtype
resultType无法查询结果映射到pojo对象的pojo属性中,根据对结构集查询遍历的需要选择使用resultType还是resultMap。适用于单表查询。
三、类型适用不同
1、resultmap:mybatis中在查询进行select映射的时候,返回类型可以用resultType,也可以用resultMap,只不过采用resultMap时需要对该resultMap进行自定义映射处理,即采用<resultMap>元素定义映射。
2、resulttype:resultType是直接表示返回类型的,而resultMap则是对外部ResultMap的引用,但是resultType跟resultMap不能同时存在。