一对多处理
按照查询嵌套处理
<resultMap id="TeacherStudent" type="Teacher">
<result property="id" column="id"/>
<result property="name" column="name"/>
<!--复杂的属性需要单独处理 对象:association 集合:collection-->
<collection property="students" column="id" javaType="ArrayList" ofType="Student" select="getStudentByTeacherId"/>
</resultMap>
<select id="getStudentByTeacherId" resultType="Student">
select * from student where tid = #{tid}
</select>
<select id="getTeacher" resultMap="TeacherStudent">
select * from teacher where id = #{tid}
</select>
按照结果嵌套处理
<resultMap id="TeacherStudent2" type="Teacher">
<result property="id" column="tid"/>
<result property="name" column="tname"/>
<!--复杂的属性需要单独处理 对象:association 集合:collection-->
<collection property="students" ofType="Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<result property="tid" column="tid"/>
</collection>
</resultMap>
<select id="getTeacher2" resultMap="TeacherStudent2">
select s.id sid, s.name sname, t.name tname, t.id tid
from student s, teacher t
where s.tid = t.id and t.id = #{tid}
</select>
小结
- 关联-association [多对一]
- 集合-collection [一对多]
- javaType : 用来指定实体类中属性的类型
- ofType : 用来指定映射到List或者集合中的pojo类型, 泛型中的约束类型
注意
-
保证SQL的可读性, 尽量通俗易懂
-
注意一对多和多对一中, 属性名和字段的问题
-
善用日志排查问题