spring-boot - 如何将参数传递给子查询
问题描述
我只是使用 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”的商店
解决方案
该查询不起作用,因为该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 的查询可以(并且应该使用。
推荐阅读
- embedded - 为什么 i2cdetect 0 不返回地址
- wpf - 如何将listView的selectedItem值传递到wpf MVVM中的另一个页面
- excel - 如何在mule 3中将新工作表附加到现有的excel文件
- java - 将 java 方法转换为 HTTP 请求
- clojure - 如何在 Clojure 的嵌套数组映射中找到键的路径?
- reactjs - 反应下拉值
- python - 检查 Jupyter notebook 中命令的 CPU 利用率
- sql - 更新前的 Firebird 触发器(使用时间戳更新列)
- typescript - 未实例化类的接口
- heroku - Cloudflare CDN 背后的 Heroku 应用程序在以色列出现 DNS 错误 1016 大约一个月