I have three tables created with Hibernate. Product is the parent while barcodes is a collection end price is a child (one to many) of products.
@NotBlank private String ref; @ElementCollection(fetch = FetchType.EAGER) @CollectionTable(name = "products_barcodes") @Fetch(FetchMode.SELECT) private List<String> barcodes; @OneToMany(mappedBy = "parent", fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true) private List<PriceEntity> prices;
I’m trying to query starting from the child (Price). I was able to query on a string but now i would like to query on the collection s element.
Specifications<PriceEntity> specifications = where(hasTenant(tid)); if (isNotBlank(ref)) { specifications = specifications.and(hasRef(ref)); } if (isNotBlank(barcode)) { specifications = specifications.and(hasBarcode(barcode)); } /*********************************/ public static Specification<PriceEntity> hasRef(final String ref) { return new Specification<PriceEntity>() { @Override public Predicate toPredicate(Root<PriceEntity> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) { return criteriaBuilder.equal(root.<PriceEntity>get("parent").get("ref"), ref); } }; } public static Specification<PriceEntity> hasBarcode(final String barcode) { return new Specification<PriceEntity>() { @Override public Predicate toPredicate(Root<PriceEntity> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) { return criteriaBuilder.equal(root.<PriceEntity>get("parent").get("barcodes"), barcode); } }; }
how would you write the specification? The one above is not working, i get this exception at runtime:
"IllegalArgumentException: Parameter value [8003921360408] did not match expected type [java.util.Collection (n/a)]"
Thanks
Advertisement
Answer
Question solved by Thomas s comment.
For collections criteriaBuilder.isMember
should be used.