1

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

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

4

1 回答 1

1

这不是直接可能的,但您可以使用Blaze-Persistence Entity Views来实现。

我创建了该库以允许在 JPA 模型和自定义接口或抽象类定义模型之间轻松映射,例如 Spring Data Projections on steroids。这个想法是您以您喜欢的方式定义您的目标结构(域模型),并通过 JPQL 表达式将属性(getter)映射到实体模型。

使用 Blaze-Persistence Entity-Views 的用例的 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 Data 集成允许您几乎像 Spring Data Projections 一样使用它:https ://persistence.blazebit.com/documentation/entity-view/manual/en_US/index.html#spring-data-features

Page<ProductDto> findAll(Pageable pageable);

最好的部分是,它只会获取实际需要的状态!

在你的情况下,你可以使用这样的排序:sort=highestValuem,ASC

于 2021-04-06T12:08:04.403 回答