1、按照查询嵌套处理
<select id="getTeacher2" resultMap="TeacherStudent2">
select * from teacher where id=#{tid}
</select>
<resultMap id="TeacherStudent2" type="Teacher">
<collection property="students" javaType="ArrayList" ofType="Student" select="getStudentByTeacherId" column="id"></collection>
</resultMap>
<select id="getStudentByTeacherId" resultType="Student">
select * from student where tid=#{tid}
</select>
2、按照结果嵌套处理
<select id="getTeacher" resultMap="TeacherStudent">
select s.id sid,s.name sname,t.id tid,t.name table_name
from student s,teacher t
where s.tid=t.id AND t.id=#{tid}
</select>
<resultMap id="TeacherStudent" type="Teacher">
<result property="id" column="tid"></result>
<result property="name" column="tname"></result>
<collection property="students" ofType="Student">
<result property="id" column="sid"></result>
</collection>
</resultMap>
3、小结
-
在多对一的时候使用关联association,在一对多的时候使用集合collection
-
要保证sql的可读性,尽量通俗易懂
-
如果问题不好排查可以使用日志,建议使用Log4j
-
javaType和ofType区别
-
javaType用来指定实体类中属性的类型
-
ofType用来指定映射到List或者集合中pojo类型,是泛型中的约束类型
-