1.输出结果为简单类型(8个基本类型+String)
resultType="int"
mapper.xml文件中:
<select id="queryStudentCount" resultType="int">
select count(*) from student2
</select>
mapper接口中:
Integer queryStudentCount();
测试:
StudentMapper studentMapper = session.getMapper(StudentMapper.class);
Integer count = studentMapper.queryStudentCount();// 接口中的方法->SQL语句
System.out.println(count);
session.close();
返回结果为:
9
2.输出结果为对象类型
和简单对象类似,定义接口时方法返回值为实体类对象,sql语句返回对象.
3.输出结果为多个对象,集合类型
此时mapper.xml中resultType还是指定为对象类型,但是接口中的方法要指定集合类型,如list集合
mapper.xml:
<select id="queryAllStudents" resultType="student" >
select * from student2
</select>
mapper接口:
List<Student> queryAllStudents();
测试:
StudentMapper studentMapper = session.getMapper( StudentMapper.class) ;
List<Student> students = studentMapper.queryAllStudents() ;//接口的方法->SQL
System.out.println(students);
session.close();
测试结果:集合对象能打印输出
4.输出结果为Map类型(hashmap)
mapper.xml:
<!-- 输出参数为HashMap 但是只能查询一个学生的信息(去掉where条件,报错)
Expected one result (or null) to be returned by selectOne(), but found: 8
-->
<select id="queryStudentOutByHashMap" resultType="HashMap">
select stuno ,stuname from student2 where stuno=1
</select>
mapper接口:
//输出参数为HashMap 但是只能输出一个学生的信息
HashMap<String, Object> queryStudentOutByHashMap();
测试:
StudentMapper studentMapper = session.getMapper(StudentMapper.class);
HashMap<String, Object> map = studentMapper.queryStudentOutByHashMap();// 接口的方法->SQL
System.out.println(map);
session.close();
上面输出结果为:{STUNAME=zs, STUNO=1}
如果select语句写成:select stuno "no",stuname "name" from student2 where stuno=1
则结果为{no=1, name=zs}.
说明当我们给输出结果取别名时,map就会把别名当作key,否则就按照原来的字段名为key。
另外,这个sql语句要加where条件,因为接口方法的返回值类型为HashMap(String,Object),虽然我们知道map本身就是一个集合,但是在这里面,一个hashmap表示一个Student,不加where条件,会查询出多条结果(即多个Student),所以会报:
Expected one result (or null) to be returned by selectOne(), but found: 8
要想返回多条结果集,就要使用List<HashMap<String,Object>>接收。结果就会输出一个List中的多个HashMap集合,即多个Student对象。