如何对ElementCollection和CollectionTable使用CriteriaQuery

hev*_*evi 8 java spring hibernate jpa criteria-api

我有一个非常简单的实体产品,它有代码,名称和标签.标签存储在另一个带有product_id和tag列的表(product_tag)中.

我需要使用CriteriaQuery搜索带有某些标签的产品.举个例子,我想找到具有'fruit'和'red'标签的产品.

使用spring 4.1.x,spring-data-jpa 1.8和hibernate 4.2.x.

我的实体只是;

@Entity
@Table(name = "product", uniqueConstraints ={
        @UniqueConstraint(columnNames = "code")
    }
)
@NamedQueries({
        @NamedQuery(name = "Product.findAll", query = "select p from Product p")
})
public class Product extends EntityWithId {

    @Column(name = "code", length = 128)
    private String code;

    @Column(name = "name", length = 512)
    protected String name;

    @ElementCollection(fetch = FetchType.EAGER)
    @CollectionTable(name="product_tag", joinColumns=@JoinColumn(name="product_id"))
    @Column(name="tag")
    private Set<String> productTags = new HashSet<>();

}
Run Code Online (Sandbox Code Playgroud)

这是我如何启动搜索的代码;

private void search() {

    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Product> criteriaQuery = builder.createQuery(Product.class);
    Root<Product> product = criteriaQuery.from(Product.class);

    Predicate where = builder.conjunction();

    if (!StringUtils.isEmpty(nameSearch.getValue())) {
        where = builder.and(where, builder.like(product.<String>get("name"), nameSearch.getValue() + "%"));
    }

    if (!StringUtils.isEmpty(codeSearch.getValue())) {
        where = builder.and(where, builder.like(product.<String>get("code"), codeSearch.getValue() + "%"));
    }

    if (!StringUtils.isEmpty(tagsSearch.getValue())) {
         //Util.parseCommaSeparated returns Set<String>
        where = builder.and(where, product.get("productTags").in(Util.parseCommaSeparated(tagsSearch.getValue())));
    }

    criteriaQuery.where(where);
    List<Product> resultList = entityManager.createQuery(criteriaQuery).getResultList();

}
Run Code Online (Sandbox Code Playgroud)

但是,当我运行搜索标签'fruit'时,我得到一个例外

java.lang.IllegalArgumentException: Parameter value [fruit] did not match expected type [java.util.Set (n/a)]
Run Code Online (Sandbox Code Playgroud)

我真的很想使用CriteriaQuery for ElementCollection和CollectionTable.

Don*_*ler 13

productTags 映射到单独的表,因此您需要在查询中与该表连接.

...

if (!StringUtils.isEmpty(tagsSearch.getValue())) {
     //Util.parseCommaSeparated returns Set<String>
    where = builder.and(where, product.join("productTags").in(Util.parseCommaSeparated(tagsSearch.getValue())));
}

...
Run Code Online (Sandbox Code Playgroud)

请注意product.join("productTags")而不是product.get("productTags")

  • 此外,这会创建一种OR搜索,在tagsSearch中有fuit和red,所有的红色和水果都会返回.对于AND搜索,我确实为每个tagsSearch明确创建了AND语句.对于那些斗争:) (2认同)