gpt4 book ai didi

java - Spring Data (Hibernate) 动态 WHERE 子句

转载 作者:行者123 更新时间:2023-12-01 18:05:41 25 4
gpt4 key购买 nike

我有一个像这样的存储库

@Repository
public interface LeadRequestRepository extends PagingAndSortingRepository<LeadRequest, UUID> {

@Query(value = "SELECT * FROM lead_request WHERE product IN :products AND current_status in :status", nativeQuery = true)
List<LeadRequest> findLeadRequests(@Param("products") List<String> products, @Param("status") List<String> status);

}

在此查询中,状态可以为 null 或空列表。
在这种情况下,查询必须返回所有状态(NEW、APPROVED、REJECTED 等)。换句话说,查询必须变为 SELECT * FROM Lead_request WHERE Product IN :products 并且没有 status 子句。
我也很困惑,因为我使用 IN 子句,所以我无法使用 JPA 示例 API

如何使用 hibernate 和 jpa 实现此目的?

最佳答案

有两个选项:

  1. 您将有两个 JPQL/ native 查询,并根据 null 条件调用其中一个查询。
  2. 更好的选择是使用 JPA 标准查询。 Spring Data JPA 为称为 Specifications 的 JPA 标准查询提供抽象。看看Spring Data JPA docs here

关于java - Spring Data (Hibernate) 动态 WHERE 子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60562756/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com