J
J
Jake Taylor2021-11-09 17:06:28
Hibernate
Jake Taylor, 2021-11-09 17:06:28

How to make query with JOIN in CriteriaQuery?

There are 2 entity tables and a third table (gift_certificate_to_tag_relation) for a many-to-many relationship: You
618a8077bede3230947735.png

need to get a list tagby gift_certificate. For this case, I made a SQL query:

SELECT tag.name FROM Tag tag JOIN gift_certificate_to_tag_relation relation on tag.id = relation.tag_id WHERE relation.gift_certificate_id = 13;


Having remade it for Hibernate entities, it will take the form:
SELECT tag FROM Tag AS tag JOIN GiftCertificateToTagRelation AS relation ON relation.tag = tag WHERE relation.giftCertificate = :giftCertificate";


Now I'm trying to make a request with CriteriaQuery:
CriteriaQuery<Tag> cq = cb.createQuery(Tag.class);
Root<Tag> rootTag = cq.from(Tag.class);

// JOIN GiftCertificateToTagRelation AS relation ON relation.tag = tag
Join<Tag, GiftCertificateToTagRelation> join = rootTag.join(ParameterName.GIFT_CERTIFICATE);

// WHERE relation.giftCertificate = :giftCertificate
Predicate condition = cb.equal(join.get(ParameterName.GIFT_CERTIFICATE), gc);

// Full SQL query: SELECT tag FROM Tag AS tag JOIN GiftCertificateToTagRelation AS relation ON relation.tag = tag WHERE relation.giftCertificate = :giftCertificate
cq.select(rootTag).where(condition);

return em.createQuery(cq)
                .getResultStream()
                .collect(Collectors.toSet());


But I get an error when running:
Unable to locate Attribute  with the the given name [giftCertificate] on this ManagedType

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