1.使用结果映射主要是为了解决表的字段名跟对象属性不对等。多张表的前提下使用(一对一,一对多,多对一)
1.1多对一进行查询。
嵌套结果
<resultMap id="studentMap" type="student">
property指的是java中的字段属性,column指的是查询的数据库中列表
<id property="id" column="id"></id>
<result property="name" column="name"></result>
<result property="hobby" column="hobby"></result>
association里面嵌套一方,有多个一方则嵌套多个association
<association property="teacher" javaType="teacher">
<id property="id" column="tid"></id>
<result property="name" column="tname"></result>
<result property="age" column="tage"></result>
</association>
</resultMap>
<select id="findAll" resultMap="studentMap">
SELECT
s.id,
s. NAME,
s.hobby,
t. NAME tname,
t.age tage,
t.id tid
FROM
t_stu s
JOIN t_tea t ON s.tea_id = t.id
</select>-->
嵌套查询
<resultMap id="studentMap" type="student">
<!--property指的是java中的字段属性,column指的是查询的数据库中列表-->
<id property="id" column="id"></id>
<result property="name" column="name"></result>
<result property="hobby" column="hobby"></result>
<!--
association里面嵌套一方,有多个一方则嵌套多个association
嵌套查询,先查询出多方的所有数据,再根据多方中一方中的id,查找出一方的数据
-->
<!--这里column对应的应该是外键id,它是引用student表中的外键id-->
<association property="teacher" column="tea_id" javaType="teacher" select="queryTeacherByTId">
</association>
</resultMap>
<select id="findAll" resultMap="studentMap">
select * from t_stu s limit
</select>
<select id="queryTeacherByTId" parameterType="long" resultType="teacher">
<!--括号里面id的写法无影响-->
select * from t_tea where id=#{id}
</select>
1.2一对多进行查询(一对多中可以使用分页查询,但多对一中不能使用)
嵌套结果
<!--<resultMap id="teacherMap" type="teacher">
<id property="id" column="id"></id>
<result property="name" column="name"></result>
<result property="age" column="age"></result>
一对多使用collection property Java中的返回值 javaType 返回的类型 ofType 泛型中的属性
<collection property="students" javaType="arraylist" ofType="student">
<id property="id" column="sid"></id>
<result property="name" column="sname"></result>
<result property="hobby" column="shobby"></result>
</collection>
</resultMap>
<!–引用resultMap中的id–>
<select id="findAll" resultMap="teacherMap">
SELECT
t.id,
t. name,
t.age,
s.id sid,
s.name sname,
s.hobby shobby
FROM
t_tea t
JOIN t_stu s ON t.id = s.tea_id
</select>-->
嵌套结果
<resultMap id="teacherMap" type="teacher">
<id property="id" column="id"></id>
<result property="name" column="name"></result>
<result property="age" column="age"></result>
<!--
一对多使用collection property Java中的返回值 javaType 返回的类型 ofType 泛型中的属性
column中的id来自一方中的id,根据这个去找多方中的数据
-->
<collection property="students" column="id" javaType="arraylist" ofType="student" select="queryStudentById">
</collection>
</resultMap>
<!--引用resultMap中的id-->
<select id="findAll" resultMap="teacherMap">
select t.id,t.age,t.name from t_tea t limit 0,2
</select>
<!--根据自身数据库中的表的外键id-->
<select id="queryStudentById" parameterType="long" resultType="student">
select * from t_stu where tea_id=#{id}
</select>