今天学习mybaties时学到了当使用mybaties查询多对一的结果时怎么处理。
当我们要执行查询语句
select s.id ,s.name ,t.name from student s,teacher t where s.tid = t.id
时,会发现其查询使用的参数包含在student和teacher两个对象里面,这种情况下我们的resultType填写student时会无法获取到teacher对象的参数,所以我们采用结果映射嵌套的办法,将teacher对象里面的参数映射出来
<!--
在查询结果中含有其他类的属性时怎么办?(student类中含有teacher对象,要查询的结果为student的id student的name teacher的name)
1.通过结果集映射resultMap写出各个结果映射result 当轮到写teacher对象的结果映射时不用result 用association 在其中嵌套result 写明映射关系
-->
<resultMap id="teacherStudent" type="com.zyy.pojo.Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<association property="teacher" javaType="com.zyy.pojo.Teacher">
<result property="name" column="tname"/>
</association>
</resultMap>
<select id="getStudentList" resultMap="teacherStudent" >
select s.id sid,s.name sname,t.name tname from student s,teacher t where s.tid = t.id
</select>
以下是多对一的处理
<resultMap id="teacherStudent" type="com.zyy.pojo.Teacher">
<result property="id" column="tid"/>
<result property="name" column="tname"/>
<collection property="studentList" ofType="com.zyy.pojo.Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
</collection>
</resultMap>
<select id="getTeacher" resultMap="teacherStudent">
select t.id tid,t.name tname,s.id sid,s.name sname from student_teather.teacher t,student_teather.student s where t.id=s.tid and t.id=1;
</select>
注意一对多的时候因为参数为对象所以使用
<association property="teacher" javaType="com.zyy.pojo.Teacher">
<result property="name" column="tname"/>
</association>
然后一对多的时候因为参数为List集合所以使用
<collection property="studentList" ofType="com.zyy.pojo.Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
</collection>
注意这两者申明类型的区别