1.简单类型(8个基本+String)
<select id="queryStudentCount" resultType="int">
select count(*) from student
</select>
2.输出参数为实体对象类型
<select id="queryStudentByStuno" parameterType="int" resultType="student">
select * from student where stuno = #{stuno}
</select>
3.输出参数为实体对象类型的集合
<select id="queryAllStudents" resultType="student">
select * from student
</select>
<resultMap type="student" id="studentResult">
<!-- 分为主键id,非主键result -->
<id property="id" column="stuno"/>
<result property="name" column="stuname"/>
<result property="stuAge" column="stuage"/>
<result property="graName" column="graname"/>
<result property="stuSex" column="stusex" javaType="boolean" jdbcType="INTEGER"/>
</resultMap>
<select id="queryStudentByStuno" parameterType="int" resultMap="studentResult">
select * from student where stuno = #{stuno}
</select>
<select id="queryStuOutByHashMap" parameterType="int" resultType="student">
select stuno "no", stuname "name" from student where stuno = #{stuno}
</select>
虽然输出类型为集合,但是resultType依然写集合的元素类型(resyltType=“Student”)
resultType
resultMap:实体类的属性和数据表的字段: 类型、名字不同时(例如:stuno和id)
注意
当属性名和字段名不一致时,除了使用resultMap以外,还可以使用resultType+HashMap
如果如果10个字段,但发现某一个字段结果始终为默认值(0,0.0,null),则可能是 表的字段和类的属性名字写错
<resultMap type="student" id="studentResult">
<!-- 分为主键id,非主键result -->
<id property="id" column="stuno"/>
<result property="name" column="stuname"/>
<result property="stuAge" column="stuage"/>
<result property="graName" column="graname"/>
<result property="stuSex" column="stusex" javaType="boolean" jdbcType="INTEGER"/>
</resultMap>
<select id="queryStudentByStuno" parameterType="int" resultMap="studentResult">
select * from student where stuno = #{stuno}
</select>
<select id="queryStuOutByHashMaps" parameterType="int" resultType="HashMap">
select stuno "no", stuname "name" from student where stuno = #{stuno}
</select>
4.输出参数类型为HashMap
<!-- 别名作为map的key-->
<select id="queryStuOutByHashMap" parameterType="int" resultType="HashMap">
select stuno "no", stuname "name" from student where stuno = #{stuno}
</select>
HashMap<String, Object> queryStuOutByHashMap(int stuno);
public static void queryStuOutByHashMap() throws IOException {
Reader reader = Resources.getResourceAsReader("conf.xml");
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);
SqlSession session = sessionFactory.openSession();
studentMapper studentmapper = session.getMapper(studentMapper.class);
HashMap<String, Object> studentMap = studentmapper.queryStuOutByHashMap(5);
System.out.println(studentMap);
session.close();
}
HashMap本身是一个集合,可以存放多个元素,
但是根据提示发现返回值为HashMap时,查询的结果只能是1个学生(no, name);
原因是:一个HashMap对应一个学生的多个元素(多个属性)即一个map,一个学生
二维数组
[
{1,zs,20,xa}, 一个HashMap对象
{2,ls,20,bj},
{3,ww,20,tj}
]
接口改为数组类型
List<HashMap<String, Object>> queryStuOutByHashMaps(int stuno);