mybatis annotation实现一对多查询

一个库位包含多种物料,需要查询库位的库存信息,即每个库位中包含的物料号,物料名称,数量 。这种情况可以有三种方法:

  1. java for循环实现
  2. 存储过程实现
  3. sql复杂查询

第一种方法效率太低,第二种方法对于存储过程不熟的童鞋需要学习成本。这里介绍最常用的第三种方法。

需要返回的数据结构:

@Data
public class BinInfo {
    
    
    private int id;//库位id
    private String binName;//库位名
    private int maxStock;//库位最大容量
    private int status;//库位状态
    private int groupName;//库位组
    private int priority;//库位优先级
    private List<StockSumDto> goodsInfoList;
}

其中StockSumDto定义了物料号,物料名称,数量:

@Data
@ApiModel(description = "库存汇总Dto")
public class StockSumDto {
    
    

    @ApiModelProperty(value = "物料号")
    private String partNo;

    @ApiModelProperty(value = "物料名称")
    private String goodsName;

    @ApiModelProperty(value = "物料数量")
    private int goodsCounts;

}

Mapper层的查询需要两步

第一步
@Select("select id as id,b_name as binName,group_name as groupName,priority as priority,is_empty as status," +
            "max_stock as maxStock from dbo.bin order by id asc")
    @Results(value = {
    
    
            @Result(property="id", column="id"),
            @Result(property="binName", column="binName"),
            @Result(property="groupName", column="groupName"),
            @Result(property="priority", column="priority"),
            @Result(property="status", column="status"),
            @Result(property="maxStock", column="maxStock"),
            @Result(property="goodsInfoList", javaType=List.class,column = "id",
                    many=@Many(select="findGoodsInfoList"))
    })
    List<BinInfo> getBinInfoByRName();

:@Result中property 为dto中的属性,column为数据表中的表,如果查询语句中使用了别名,这里一定一定一定要使用别名,不然导致查出来的结果中StockSumDto有值 ,但bin的信息丢失了。

第二步
@Select("SELECT s.part_no as partNo,sum(s.stock) as goodsCounts,g.name as goodsName from storage s " +
            "join goods g on g.part_no = s.part_no where s.b_id = #{id} group by s.part_no ,g.name ")
    List<StockSumDto> findGoodsInfoList(Integer id);

注:第一步中的@Many关联第二步的查询,关联字段为id.

猜你喜欢

转载自blog.csdn.net/hongyinanhai00/article/details/109755552