在我的 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 规范,我可以构建一个查询来根据成分标准获取 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 字段对其进行排序。显然,我问的是如何在数据库上做,而不是在业务逻辑中。