[英]Spring Data JPA - Query with Specification (Join and IN)
我已经组装了以下类Specification:
public ItemVendedorSpecification(String descricao, List<Long> categorias, List<Long> fabricantes, List<Long> vendedores) {
super();
this.descricao = descricao;
this.categorias = categorias;
this.fabricantes = fabricantes;
this.vendedores = vendedores;
}
@Override
public Predicate toPredicate(Root<ItemVendedor> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
if (!descricao.isEmpty()) {
String PalavraChave[] = descricao.split(" ");
for (String filtro : PalavraChave) {
predicates.add(builder.like(builder.upper(root.get("id").get("produto").get("descricaoDetalhada")), "%" + filtro.toUpperCase() + "%"));
}
}
predicates.add(builder.isTrue(root.get("disponivel")));
if(!fabricantes.isEmpty()) {
predicates.add(root.get("id").get("produto").get("fabricante").get("id").in(fabricantes));
}
if(!vendedores.isEmpty()) {
predicates.add(root.get("id").get("vendedor").get("id").in(vendedores));
}
if(!categorias.isEmpty()) {
predicates.add(root.join("id").get("produto").get("categorias").get("id").in(categorias));
}
return builder.and(predicates.toArray(new Predicate[1]));
}
}
除了插入类别标准的谓词外,几乎所有谓词都在起作用。 它不起作用,我很难创建它。
以这种方式返回以下错误:
"Illegal attempt to dereference path source [null.produto.categorias] of basic type; nested exception is java.lang.IllegalStateException: Illegal attempt to dereference path source [null.produto.categorias] of basic type"
如果有人可以帮助我制作这个作品吗?
下面是ItemSeller类的详细信息:
public class ItemVendedor implements Serializable{
private static final long serialVersionUID = 1L;
private ItemVendedorPK id = new ItemVendedorPK();
private BigDecimal preco;
private Boolean disponivel;
private Date dt_insert;
private Date dt_update;
private BigDecimal desconto;
public ItemVendedor() {
}
public ItemVendedor(Produto produto, Vendedor vendedor, BigDecimal preco, BigDecimal desconto ,Boolean disponivel) {
super();
this.id.setProduto(produto);
this.id.setVendedor(vendedor);
this.preco = preco;
this.disponivel = disponivel;
this.desconto = desconto;
}
//GETs and SETs
正如你可以看到它有一个名为id字段是一个对组成关键Vendedor vendedor
和Produto produto
。
在Produto类中,我有一个List Categorias。 一个产品可以属于几个类别。
反过来,类别类别具有id.
我想在规范中输入的是一种获取所有ItemVendedor的方法,这些ItemVendedor在其类别列表中具有某些类别,而我在另一个列表List Categorias中引用了该类别作为参数。
我弄清楚了。 我以错误的方式使用查询。 以下是解析代码:
predicates.add (root.join ("id") join ("product") join ("categories") get ("id") in (categories));
这样我们就可以进行验证,以了解产品是否具有参数内的某些类别对于实现某些联接是必需的。
第一个Join与类代码中作为id的关系有关,ItemSeller表中的该字段实际上是复合键( @ Embeddable
Embeddable)的类,因此该类必须与Products类进行连接,其中具有“类别”字段。
因此,我们可以获取每种产品的类别列表,并在知道的查询参数内是否有此列表的任何元素时进行购买。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.