public class teacher2 {
private Integer id;
private String name;
private int dep_id;
}
public class department {
private Integer id;
private String name;
private ArrayList<teacher2> ts;
}
collection:处理有“很多个”类型,其属性用法与association一致
<!--当一个bean中包含其他bean集合时, -->
<resultMap type="department" id="myTeaPlus">
<id column="id" property="id" />
<id column="name" property="name" />
<collection property="ts" select="com.operation.TeacherOperation.selectTsByID"
column="id" >
<id column="name" property="name" />
<id column="id" property="id" />
</collection>
</resultMap>
<resultMap type="department" id="myTeaPlus1">
<id column="id" property="id" />
<id column="name" property="name" />
<!--
扩展:多列的值传递过去
将多列的值封装成map传递
column="{key1=column1,key2=column2}"
在config中已经配置了默认的加载方式为懒加载,但是我们有时特殊需求,还是希望快加载,可用fetchTpye属性
-->
<collection property="ts" select="com.operation.TeacherOperation.selectTsByID"
column="{dep_id=id}" fetchType="eager" >
<id column="name" property="name" />
<id column="id" property="id" />
</collection>
</resultMap>
<select id="selectdepByID" resultMap="myTeaPlus">
select *
from tb_Department
where id=#{id};
</select>
<resultMap type="department" id="myTeaPlus2">
<id column="id" property="id" />
<id column="name" property="name" />
<collection property="ts" ofType="teacher2" >
<id column="tname" property="name" />
<id column="depid" property="dep_id" />
<id column="tid" property="id" />
</collection>
</resultMap>
<select id="selectdepByID2" resultMap="myTeaPlus2">
select tb_department.id id,tb_department.name,tb_teacher2.id tid,tb_teacher2.name tname,tb_teacher2.dep_id depid
from tb_department,tb_teacher2
where tb_teacher2.dep_id=tb_Department.id and tb_department.id=#{id};
</select>
MyBatis实现一对多有几种方式,怎么操作的?
有联合查询和嵌套查询。联合查询是几个表联合查询,只查询一次,通过在resultMap里面的collection节点配置一对多的类就可以完成;嵌套查询是先查一个表,根据这个表里面的 结果的外键id,去再另外一个表里面查询数据,也是通过配置collection,但另外一个表的查询通过select节点配置。