resultType 属性可以指定结果集的类型,它支持基本类型和实体类类型。它和 parameterType 一样,如果注册过类型别名的,可以直接使用别名。没有注册过的必须 使用全限定类名。当是实体类名称时,还有一个要求,实体类中的属性名称必须和查询语句中的列名保持一致,否则无法 实现封装。
例如返回是基本类型:
<select id="findAll" resultType="com.Ycy.domain.User"> select * from user </select>当实体类的属性名称和查询语句中(数据库中列名)相同,这样是可以封装的。
但是当实体类的属性名和查询语句中(数据库中列名)不相同时,就无法封装的,解决方法有两种如下:
第一种:
我们把查询语句的字段名取别名来对应实体类中的属性名 注意:mysql在windows上是不区分大小写的
<select id="findAll" resultType="com.Ycy.domain.User"> select id as userId,username as userName,birthday as userBirthday, sex as userSex,address as userAddress from user </select>但是当查询语句别较多时,取别名的方法就显得非常麻烦,修改sql语句比较频繁,这就使用第二种方法比较来得实在。
接下来来了解一下resultMap,第二种方法就是使用resultMap来解决的
resultMap的作用:
1、resultMap 标签可以建立查询的列名和实体类的属性名称不一致时建立对应关系。从而实现封装。 在 select 标签中使用 resultMap 属性指定引用即可。
2、resultMap 可以实现将查询结果映射为复杂类 型的 pojo,比如在查询结果映射对象中包括 pojo 和 list 实现一对一查询和一对多查询。
<select id="findAll" resultMap="userMap"> select * from user </select> <resultMap type="com.Ycy.domain.User" id="userMap"> <id column="id" property="userId"/> <result column="username" property="userName"/> <result column="sex" property="userSex"/> <result column="address" property="userAddress"/> <result column="birthday" property="userBirthday"/> </resultMap>id 标签:用于指定主键字段
result 标签:用于指定非主键字段
column 属性:用于指定数据库列名
property 属性:用于指定实体类属性名称
实现一对一或者一对多的查询的结果封装
public class student { private int id; private String name; private teacher teachers; } <?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="cn.com.Ycy.mybatsi.dao.studentDao"> <select id="getstudents" resultMap="student_teacher"> SELECT stu.id,stu.name,teacher.name AS teacher_name,teacher.id AS teacher_id FROM student stu,teacher WHERE stu.tid = teacher.id </select> <resultMap id="student_teacher" type="cn.com.Ycy.mybatsi.domain.student"> <id column="id" property="id"/> <result column="name" property="name"/> <association property="teachers" javaType="cn.com.Ycy.mybatsi.domain.teacher"> <id column="teacher_id" property="tid"/> <result column="teacher_name" property="tname"/> </association> </resultMap> </mapper>具体请参考 Mybatis联合查询详解。