Spring 数据规范 orderBy 子查询

Spring Data Specification orderBy subquery

在我的 MySql 项目中,我得到了这个包含 3 个实体的特定模型:Prodotto 和许多子项 QuotaIngrediente,后者也是 Ingrediente 的多对一子项。我所有的关系都是双向的。 他们都得到了一个自动生成的整数 Id,并删除了其他字段以专注于有趣的字段。

@Entity
public class Prodotto {
    private List<QuotaIngrediente> listaQuoteIng = new ArrayList<QuotaIngrediente>();

    @OneToMany(mappedBy = "prodotto", cascade = CascadeType.ALL, orphanRemoval = true)
    public List<QuotaIngrediente> getListaQuoteIng() {
        return listaQuoteIng;
    }
@Entity
public class QuotaIngrediente{

    private Prodotto prodotto;

    private Ingrediente ing;

    private Double perc_ing;

    @ManyToOne
    @JoinColumn(name = "prodotto")
    public Prodotto getProdotto() {
        return prodotto;
    }

    @ManyToOne
    @JoinColumn(name = "ing")
    public Ingrediente getIng() {
        return ing;
    }
@Entity
public class Ingrediente {
    private Set<QuotaIngrediente> quoteIng = new HashSet<QuotaIngrediente>();

    @OneToMany(mappedBy = "ing", cascade = CascadeType.ALL, orphanRemoval = true)
    public Set<QuotaIngrediente> getQuoteIng() {
        return quoteIng;
    }

我正在使用 SpringData 规范,我可以构建一个查询以根据 Ingrediente 标准获取 Prodotto,这样:

public static Specification<Prodotto> getProdottoByIngSpec (String ing) {

    if (ing != null) {
        return (root, query, criteriaBuilder) -> {
            query.groupBy(root.get(Prodotto_.id));

            return criteriaBuilder.like(((root.join(Prodotto_.listaQuoteIng))
                                                .join(QuotaIngrediente_.ing))
                                                .get(Ingrediente_.nome), "%"+ing+"%");
        };

它按预期工作,但现在我想按该特定成分的 QuotaIngrediente perc_ing 字段对其进行排序。 显然我问的是如何在数据库上做这件事,而不是在业务逻辑上。

由于我的错误假设,我一直在努力解决一个错误的问题。解决方案是最简单的。只需按 orderBy CriteriaQuery 方法排序。我用来搜索的查询已经过滤了 QuotaIngrediente,只返回符合我的搜索条件的行。那么这是我必须添加到我的规范中的唯一行:

query.orderBy(builder.desc((root.join(Prodotto_.listaQuoteIng))
                                   .get(QuotaIngrediente_.perc_ing)));