mybatis封装输出结果
resultType
resultType:执行 sql 得到 ResultSet 转换的类型,使用类型的完全限定名或别名。 注意如果返回的是集合,那应该设置为集合包含的类型,而不是集合本身。resultType 和 resultMap,不能同时使用。
1. 简单类型
接口方法:
int countStudent();
mapper文件:
<select id="countStudent" resultType="int">
select count(*) from student
</select>
2. 对象类型
接口方法:
Student selectById(int id);
mapper文件:
<select id="selectById" resultType="com.hzc.domain.Student">
select id,name,email,age from student where id=#{studentId}
</select>
tips: Dao 接口方法返回是集合类型,需要指定集合中的类型,不是集合本身。
3. Map
sql 的查询结果作为 Map 的 key 和 value。推荐使用Map<Object,Object>。
注意:Map 作为接口返回值,sql 语句的查询结果最多只能有一条记录。大于一条记录是错误。
接口方法:
Map<Object,Object> selectReturnMap(int id);
mapper文件:
<select id="selectReturnMap" resultType="java.util.HashMap">
select name,email from student where id = #{studentId}
</select>
resultMap
resultMap 可以自定义 sql 的结果和 java 对象属性的映射关系。更灵活的把列值赋值给指定属性。
常用在列名和 java 对象属性名不一样的情况。
使用方式:
1. 先定义 resultMap,指定列名和属性的对应关系。
2. 在<select>中把 resultType 替换为 resultMap。
<resultMap id="student" type="org.example.domain.User">
<id column="uno" property="no"></id>
<result column="uname" property="name" />
<result column="email" property="email" />
</resultMap>
<select id="selectUsers" parameterType="java.lang.String" resultMap="student">
select * from user where uname = #{name}
</select>