(十一)bean中包含其他bean集合--collection

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节点配置。
 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值