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


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

目录
  • MyBatis14:通过collection解决一对多的映射关系
      • 对象
      • 接口
      • 映射文件
      • 测试
      • 总结
      • 注意事项

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

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

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

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

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

对象

接口

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

映射文件


    
        
        
        
            
            
            
            
            
        
    
    

测试

    @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);
        }
    }

总结

collection:处理一对多映射关系

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

注意事项

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