mybatis annotation implements one-to-many query

A storage location contains multiple materials. It is necessary to query the inventory information of the storage location, that is, the material number, material name, and quantity contained in each storage location. There are three methods for this situation:

  1. java for loop implementation
  2. Stored procedure implementation
  3. sql complex query

The first method is too inefficient, and the second method requires learning costs for children's shoes who are not familiar with the storage process. Here is the third method most commonly used.

The data structure that needs to be returned:

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

Among them, StockSumDto defines the material number, material name, and quantity:

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

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

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

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

}

The query of the Mapper layer requires two steps

first step
@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();

Pit : The property in @Result is the property in dto, and the column is the table in the data table. If an alias is used in the query statement, the alias must be used here , otherwise it will cause the value of StockSumDto in the result to be found, but the value of bin The information is lost.

Second step
@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);

Note: @Many in the first step is associated with the query in the second step, and the associated field is id.

Guess you like

Origin blog.csdn.net/hongyinanhai00/article/details/109755552