Spring JPA 组合查询,每个查询具有不同的排序

Spring JPA combine queries each with different sort

我有以下实体:

@Entity(name = "Product")
@Table(name = "product")
public class Product {
  @Id
  @GeneratedValue
  private UUID id;

  private String barcode;

  private String description;

  // ... Additional fields removed for clarity

  @Min(0)
  private Integer quantity;
  @Column(insertable = false, updatable = false)
  private ZonedDateTime createdAt;

  @Column(insertable = false)
  private ZonedDateTime updatedAt;
}

我一直在摸索如何使用 Spring 数据 JPA,特别是 PagingAndSortingRepository 这样我就可以 return 可分页的产品 quantity > 0 首先 returned,quantity = 0quantity is NULL 最后 returned。所以这就像有两组,一组 quantity > 0,另一组 quantity = 0quantity is NULL。另一个约束是对于每个组,产品需要按 updatedAt 字段降序排序。

使用SQL查询,下面实现了我需要的:

SELECT * FROM (
  SELECT * FROM product WHERE quantity > 0 
  UNION
  SELECT * FROM product WHERE quantity = 0 OR quantity IS NULL
) s 
ORDER BY 
  CASE WHEN quantity > 0 THEN 1 ELSE 2 END ASC, 
  updated_at DESC;

但是当我将它写入我的存储库时class,如下所示:

  @Query(
      "SELECT p FROM ("
          + "  SELECT a FROM product a WHERE a.quantity > 0 "
          + "  UNION "
          + "  SELECT b FROM product b WHERE b.quantity = 0 OR b.quantity IS NULL "
          + ") p "
          + "ORDER BY"
          + "  CASE WHEN p.quantity > 0 THEN 1 ELSE 2 END ASC")
  Page<Product> findAll(Pageable pageable);

代码拒绝编译。在上面的代码片段中,我特别排除了 updatedAt 字段的排序,因为我希望该参数提供给 Sort class,它是 Pageable 接口的一部分。

谁能给我任何关于这个的clue/pointer?

谢谢。

好的,看起来可以通过更简单的方式实现,不需要使用子查询然后合并它们。以下就足够了:

  @Query("SELECT p FROM Product p ORDER BY CASE WHEN p.quantity > 0 THEN 0 ELSE 1 END")
  Page<Product> findAll(Pageable pageable);

updatedAt 的排序由 Sort class 在 Pageable 中处理。