首页 > 解决方案 > 如何将参数传递给子查询

问题描述

我只是使用 findAllregions 参数的 userIdx 来查找FavoriteStore

这是我的查询

@Select("SELECT * FROM region")
@Results(value = {
        @Result(property = "regionIdx", column = "regionIdx"),
        @Result(property = "stores", javaType = Store.class, column = "storeIdx",
                many = @Many(select = "com.travely.travely.mapper.StoreMapper.findFavoriteStore", fetchType = FetchType.LAZY))
})
List<Region> findAllRegions(@Param("userIdx") final Long useridx);



@Select("SELECT s.* FROM store as s NATURAL JOIN favorite as f WHERE f.userIdx=#{userIdx} AND f.isFavorite = 1")
    List<Store> findFavoriteStore(@Param("userIdx") final long userIdx);

它可以选择“findAllRegions”的区域,但不能选择“findFavoriteStore”的商店

标签: spring-bootmybatis

解决方案


该查询不起作用,因为该column属性配置不正确。

这是列属性文档的相关部分:

数据库中的列名,或包含将作为输入参数传递给嵌套语句的值的别名列标签。

如您所见,只能使用主查询结果中的列。

这意味着您需要在查询中包含人工列并@Result.column像这样使用它:

@Select("SELECT #{userIdx} userIdx, r.* FROM region r")
@Results(value = {
     @Result(property = "regionIdx", column = "regionIdx"),
     @Result(
        property = "stores", javaType = Store.class, column = "userIdx",
        many = @Many(
                 select = "com.travely.travely.mapper.StoreMapper.findFavoriteStore",
                 fetchType = FetchType.LAZY))
})
List<Region> findAllRegions(@Param("userIdx") final Long useridx);

或者,如果使用 java 8+,您可以使用默认接口方法来获取关联/集合,如下所示:

interfact MyMapper {

  @Select("SELECT * FROM region")
  @Results(value = {
        @Result(property = "regionIdx", column = "regionIdx")
  })
  List<Region> findAllRegions();

  default List<Region> findAllRegions(Long userIdx) {
      List<Region> regions = findAllRegions();
      List<Strore> favoriteStores = findFavoriteStore(userIdx);
      for(Region region:regions) {
          region.setStores(favoriteStores);
      }
      return regions;
  }

  @Select("SELECT s.* FROM store as s NATURAL JOIN favorite as f WHERE f.userIdx=#{userIdx} AND f.isFavorite = 1")
  List<Store> findFavoriteStore(@Param("userIdx") final long userIdx);

}

请注意,这不使用最喜欢的商店的延迟获取。这似乎是不需要的,因为在不需要最喜欢的商店的情况下,没有 userIdx 的查询可以(并且应该使用。


推荐阅读