resultType就是直接返回的类型,一般就是方法的返回值类型
注:这里以MyUser为实体类举例
返回类型是List<MyUser>、List<Map>、实体类型MyUser的都用resultType。需要注意的是这个时候数据库的表字段名要和实体类MyUser属性名字一样(如下图)或者是满足MyBatis定义的小驼峰命名方式(这里就不举例了),这样才适用resultType。
resultMap:查询到的结果集映射
表名和字段名不一致的情况下
适用于返回的结果类型和需要做改变的情况下使用。例如:表字段名和实体类的属性名字不符合Mybatis规则时,查询到的结果需要做转换:
public class MyUser {
private int id;
private String name;
private String sex;
}
上面的实体类和表字段名字不一样,查询结果需要用resultMap将属性名和字段名绑定(如下代码):
column:表字段名;property:是实体类的属性名
<resultMap id="userInfo" type="com.po.MyUser">
<result property="id" column="uid"></result>
<result property="sex" column="usex"></result>
<result property="name" column="uname"></result>
</resultMap>
<select id="getAllUser" resultMap="userInfo">
select * from user
</select>
将查询结果映射到其他实体类
通过如下查出的结果是MyUser实体类,但是我们可以通过resultMap将MyUser的值赋值给其他实体类(这里用People实体类举例):
MyUser实体类:
public class MyUser {
private int uid;
private String uname;
private String usex;
}
People实体类:
public class People {
private String sex;
private String name;
}
上面的两个实体类属性名都不相同的,下面我们将查询出的MyUser实体类型对象的结果赋值给People对象:
<resultMap id="PeopleInfo" type="com.po.People">
<result property="sex" column="usex"></result>
<result property="name" column="uname"></result>
</resultMap>
<select id="getAllUser" resultMap="PeopleInfo">
select * from user
</select>
我们查的表是user,我们的user表绑定的是MyUser实体类,我门需要的结果是People就只能通过resultMap将People的属性和user表的字段绑定(笼统的说也可以说是MyUser的属性和People的属性绑定,因为MyUser的属性就是和user表字段一样)
这样就能通过People对象调用toString方法将结果输出了。