J
J
Jake Taylor2021-11-19 18:40:45
Hibernate
Jake Taylor, 2021-11-19 18:40:45

What's wrong with Criteria Query?

6197c578be8f6498868495.png

What is wrong with my request? You need to select certificates that have an association with the list of tags (AND condition).

There is a request:

Set<String> tagNames = ...

CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<GiftCertificate> criteriaQuery = builder.createQuery(GiftCertificate.class);
Root<GiftCertificate> root = criteriaQuery.from(GiftCertificate.class);
Root<GiftCertificateToTagRelation> relationRoot = criteriaQuery.from(GiftCertificateToTagRelation.class);
Join<GiftCertificateToTagRelation, Tag> tagJoin = relationRoot.join(ParameterName.TAG);
Predicate condition = tagJoin.get(ParameterName.NAME).in(tagNames);
criteriaQuery.where(condition).groupBy(root);


As a result, Hibernate generates the following SQL query:
select *
from gift_certificate gc
         cross join gift_certificate_to_tag_relation r
         inner join tag t on r.tag_id = t.id
where t.name in (?, ?)
group by r.gift_certificate_id;


But he is unfaithful. You need to add "on r.gift_certificate_id = gc.id" in the line with "cross join" and you get this:
select *
from gift_certificate gc
         cross join gift_certificate_to_tag_relation r on r.gift_certificate_id = gc.id
         inner join tag t on r.tag_id = t.id
where t.name in (?, ?)
group by r.gift_certificate_id;


Then the SQL query will be executed. How to add this condition using Criteria Query?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question