如何按多页列表排序而不重复?

t9aqgxwy  于 2021-07-13  发布在  Java
关注(0)|答案(1)|浏览(411)

我最近遇到了这个问题。我有一个产品,它有一个与体积有关的值列表。示例:在此处输入图像描述实体:

  1. public class Price implements Serializable, Comparable<Price> {
  2. @Id
  3. @GeneratedValue(strategy = GenerationType.IDENTITY)
  4. private long id;
  5. @ManyToOne(fetch = FetchType.LAZY)
  6. @JoinColumn(name = "product_id")
  7. private Product product;
  8. private int valume;
  9. private int cost;
  10. @Override
  11. public int compareTo(Price o) {
  12. if (this.valume > o.getValume()) {
  13. return 1;
  14. } else if (this.valume < o.getValume()) {
  15. return -1;
  16. } else {
  17. return 0;
  18. }
  19. }
  20. }
  21. public class Product implements Serializable {
  22. @Id
  23. @GeneratedValue(strategy = GenerationType.IDENTITY)
  24. private long id;
  25. private String name;
  26. private String description;
  27. private LocalDateTime data;
  28. @OneToMany(targetEntity = Price.class, mappedBy = "product",
  29. cascade = CascadeType.ALL)
  30. @LazyCollection(LazyCollectionOption.FALSE)
  31. private List<Price> price = new ArrayList<>();
  32. }

控制器:

  1. @GetMapping
  2. public String tapePage(@PageableDefault(size = 12, sort = "data", direction = Sort.Direction.DESC) Pageable pageable,
  3. Model model){
  4. model.addAttribute("products", productService.getAllProducts(pageable));
  5. return "tape";
  6. }

问题是,如果我想按成本对产品进行排序,我将得到具有多个值的重复对象。示例- http://localhost:8080/?sort=price.valume,ASC 我如何实现一个请求,将发行不同价格的非重复产品。例如: http://localhost:8080/?sort=price[0].valume,ASC

dzjeubhm

dzjeubhm1#

这不可能直接实现,但可以通过blaze持久性实体视图实现。
我创建了这个库,以便在jpa模型和自定义接口或抽象类定义的模型之间进行简单的Map,比如spring数据在steroids上的投影。其思想是以您喜欢的方式定义目标结构(域模型),并通过jpql表达式将属性(getter)Map到实体模型。
对于blaze持久性实体视图,用例的dto模型可以如下所示:

  1. @EntityView(Product.class)
  2. public interface ProductDto {
  3. @IdMapping
  4. Long getId();
  5. String getName();
  6. String getDescription();
  7. LocalDateTime getData();
  8. @Mapping("MAX(prices.valume) OVER (PARTITION BY id)")
  9. int getHighestValuem();
  10. Set<PriceDto> getPrice();
  11. @EntityView(Price.class)
  12. interface PriceDto {
  13. @IdMapping
  14. Long getId();
  15. int getValume();
  16. int getCost();
  17. }
  18. }

查询是将实体视图应用于查询的问题,最简单的就是按id进行查询。 ProductDto a = entityViewManager.find(entityManager, ProductDto.class, id); spring数据集成允许您像spring数据投影一样使用它:https://persistence.blazebit.com/documentation/entity-view/manual/en_us/index.html#spring-数据特征

  1. Page<ProductDto> findAll(Pageable pageable);

最好的部分是,它只会获取实际需要的状态!
在您的情况下,您可以使用这样的排序: sort=highestValuem,ASC

展开查看全部

相关问题