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

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

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

public class Price implements Serializable, Comparable<Price> {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "product_id")
    private Product product;

    private int valume;
    private int cost;

    @Override
    public int compareTo(Price o) {
        if (this.valume > o.getValume()) {
            return 1;
        } else if (this.valume < o.getValume()) {
            return -1;
        } else {
            return 0;
        }
    }

}

public class Product implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    private String name;
    private String description;
    private LocalDateTime data;

    @OneToMany(targetEntity = Price.class, mappedBy = "product",
            cascade = CascadeType.ALL)
    @LazyCollection(LazyCollectionOption.FALSE)
    private List<Price> price = new ArrayList<>();    

}

控制器:

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

问题是,如果我想按成本对产品进行排序,我将得到具有多个值的重复对象。示例- 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模型可以如下所示:

@EntityView(Product.class)
public interface ProductDto {
    @IdMapping
    Long getId();
    String getName();
    String getDescription();
    LocalDateTime getData();
    @Mapping("MAX(prices.valume) OVER (PARTITION BY id)")
    int getHighestValuem();
    Set<PriceDto> getPrice();

    @EntityView(Price.class)
    interface PriceDto {
        @IdMapping
        Long getId();
        int getValume();
        int getCost();
    }
}

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

Page<ProductDto> findAll(Pageable pageable);

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

相关问题