【MyBatis】学习笔记14:通过collection解决一对多的映射关系

MyBatis14:通过collection解决一对多的映射关系

已知,一个部门对应多个员工

现要求,根据部门Id,获取部门信息和部门员工信息

下面的例子并非是部门和员工,但差不多的

下方例子存在提供商(SmbmsProvider)和订单(SmbmsBill)

要求通过提供商id获取提供商信息和订单信息(订单中可能有多个商品)

对象

image.png

image.png

接口

image.png

public SmbmsProvider getOrderByProviderId(@Param("pid") String pid);

映射文件

image.png

<!--    public SmbmsProvider getOrderByProviderId(@Param("pid") String pid);-->
    <resultMap id="getOrderByPid" type="SmbmsProvider">
        <id property="id" column="id"/>
        <result property="proName" column="proName"/>
        <collection property="smbmsBills" ofType="SmbmsBill">
            <id property="billCode" column="billCode"/>
            <result property="productName" column="productName"/>
            <result property="billCode" column="billCode"/>
            <result property="totalPrice" column="totalPrice"/>
            <result property="isPayment" column="isPayment"/>
        </collection>
    </resultMap>
    <select id="getOrderByProviderId" resultMap="getOrderByPid">
        select * from smbms_provider left join smbms_bill on smbms_provider.id=smbms_bill.providerId where smbms_provider.id=#{pid}
    </select>

测试

    @Test
    public void getBillsByProviderId(){
        SqlSession sqlSession = SqlSessionUtils.getSqlSession();
        providerMapper mapper = sqlSession.getMapper(providerMapper.class);
        SmbmsProvider result = mapper.getOrderByProviderId("2");
      System.out.println(result);
        System.out.print("公司名字:"+result.getProName()+"\n");
        for(SmbmsBill bill:result.getSmbmsBills()){
            System.out.print(" | 订单号:"+bill.getBillCode());
            System.out.print(" | 商品名称:"+ bill.getProductName());
            System.out.print(" | 商品价格:"+bill.getTotalPrice());
            String st=(bill.getIsPayment()==2)?"已付款":"未付款";
            System.out.println(" | 付款状态:"+ st);
        }
    }

image.png

总结

collection:处理一对多映射关系

--| oftype:表示该属性所对应集合中存储的数据的类型

image.png

注意事项

image.png

上述两个Id不能相同,否则会出现,查询到多条数据,但只返回一条的情况。


【Mybatis】学习笔记01:连接数据库,实现增删改

【Mybatis】学习笔记02:实现简单的查

【MyBatis】学习笔记03:配置文件进一步解读(非常重要)

【MyBatis】学习笔记04:配置文件模板

【MyBatis】学习笔记05:获取参数值的两种方式

【MyBatis】学习笔记06:各种查询所返回数据的数据类型

【MyBatis】学习笔记07:模糊查询

【MyBatis】学习笔记08:批量删除

【MyBatis】学习笔记09:批量删除

【MyBatis】学习笔记10:添加功能获取自增的主键

【MyBatis】学习笔记11:解决字段名和属性的映射关系

【MyBatis】学习笔记12:通过级联属性赋值解决多对一的映射关系

【MyBatis】学习笔记13:延迟加载(懒加载)

posted @ 2022-04-19 11:02  萌狼蓝天  阅读(72)  评论(0编辑  收藏  举报