【发布时间】:2019-01-03 04:48:44
【问题描述】:
我在存储库中定义了以下方法:
@Query("SELECT t FROM Treatment t WHERE " +
" (t.promotionCode.promotion.id=:promotionId) " +
" order by t.id desc")
Page<Treatment> findByPromotionId(@Param("promotionId")Integer id, Pageable pr);
它按预期工作:我得到了一个处理列表,其中包含属于给定促销的 PromotionCode。
但后来我需要添加第二个促销代码,因此一个治疗最多可以链接到两个促销(两个促销代码可能属于同一个促销,这不是问题)。所以我尝试将新要求添加到查询中:
@Query("SELECT t FROM Treatment t WHERE " +
" (t.promotionCode.promotion.id=:promotionId) " +
" OR " +
" (t.promotionCode2.promotion.id=:promotionId) " +
" order by t.id desc")
Page<Treatment> findByPromotionId(@Param("promotionId")Integer id, Pageable pr);
但我不会工作。生成的SQL是
select ...
from treatment treatment0_
cross join promotion_code promotionc1_
cross join promotion_code promotionc2_
where
treatment0_.promotion_code_id=promotionc1_.id and
treatment0_.promotion_code2_id=promotionc2_.id and
(promotionc1_.promo_id=? or promotionc2_.promo_id=?)
order by
treatment0_.id desc limit ?
如您所见,只要其中一个促销代码为空,则不满足条件。
一些细节,即使它们从代码中很明显:
- 除了
treatment之外,还有一个名为promotion_code的表和另一个名为promotion的表。 - 所有表都有一个数字 ID(自动递增)。
-
promotion_code_id和promotion_code2_id是指向promotion_code的 FK,它也有一个指向promotion的 FK,并且不能为空(所有促销代码都属于促销)。
我想通过任何促销代码列查找与促销相关的所有治疗。两个字段都可能为空。
我该如何解决这个问题?
【问题讨论】:
-
您确定您正在正确编译并且生成的 SQL 是您发布的方法吗??否则,
Treatment实体以及您如何将其与PromotionCode关联可能存在问题。另外,如果您可以尝试将其作为本机 sql 传递并允许映射器传回Page<Treatment> -
我对编译很有把握,因为我测试过只检查promotion_code,然后只检查promotion_code2,我在考虑
UNION但JPQL似乎不支持它 -
也许你需要手动加入推广。使用
join fetch或left join fetch。 See this question -
@Patrick 谢谢你的建议,我会试试的
标签: java postgresql spring-boot jpa jpql