在JpaRepository中相交

时间:2018-11-21 20:38:51

标签: spring spring-data-jpa jpql

我有如下的SQL查询。我想将通用的product_id,authorization_ids用于某些商人ID。 在此示例中,商人20000具有product1,authorization1和product2,authorization1,而其他商人仅具有product1,authorization1。

SELECT product_id,authorization_id  FROM ACQ_MERCHANT_PRODUCT_AUTH  WHERE merchant_Id = 20000
Intersect 
SELECT product_id,authorization_id  FROM ACQ_MERCHANT_PRODUCT_AUTH  WHERE merchant_Id = 20001
Intersect 
SELECT product_id,authorization_id  FROM ACQ_MERCHANT_PRODUCT_AUTH  WHERE merchant_Id = 20002

上面的查询给出正确的结果,即product1,authorization1。 我正在尝试在jpa中实现它:

@Repository
public interface MerchantProductAuthorizationRepository extends 
JpaRepository<MerchantProductAuthorizationEntity, Long> {

    @Query("SELECT new com.ykb.acq.application.sweep.util.ProductAuthMap(m.product.id, m.authorization.id) FROM MerchantProductAuthorizationEntity m WHERE m.merchantId IN (:merchants) GROUP BY  m.product.id, m.authorization.id")    
    List<ProductAuthMap> findIntersactionOfProductAndAuthorizations(@Param("merchants") Set<Long> merchants);

}

但是,这给了我比交叉更多的线条。 (product1,authorization1和product2,authorization2)

如何获得相同的结果?

1 个答案:

答案 0 :(得分:0)

您的HQL没有商人ID的相交逻辑。在此,我对由(m.product.id,m.authorization.id)分组的商人ID进行计数,如果该计数等于商人计数,则这对(m.product.id,m.authorization.id)总计商家设置。

SELECT new com.ykb.acq.application.sweep.util.ProductAuthMap(m.product.id, m.authorization.id) FROM MerchantProductAuthorizationEntity m WHERE m.merchantId IN (:merchants) GROUP BY  m.product.id, m.authorization.id having count(distinct m.merchantId) =:merchantsCount