How to use CriteriaQuery for ElementCollection and CollectionTable

I have a very simple Product object that has code, name and tags. Tags are stored in another table (product_tag) using product_id columns and tags.

I need to search for products with specific tags using CriteriaQuery. To give an example, I want to find products with fruit and red tags.

Using spring 4.1.x, spring -data-jpa 1.8 and hibernate 4.2.x.

My essence is simple:

@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<>();

}

here is the code as I start the search;

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();

}

However, when I run the tag flag search, I get an exception

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

I'm really interested in using CriteriaQuery for ElementCollection and CollectionTable.

+4
2

productTags , .

...

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

...

product.join("productTags") product.get("productTags")

+7

isMember(), in()

5 7

+1

Source: https://habr.com/ru/post/1584373/


All Articles