我很难寻找有关如何使用内部联接创建条件查询的良好示例。 我在下面创建了查询,该查询就是我要使用的条件。
SELECT DISTINCT *
FROM DT_DOCUMENT as document
INNER JOIN DT_TRANSLATION as translation
ON translation.language_id IN(1, 2, 3)
WHERE document.id = translation.document_id
AND document.title LIKE '%Document%';
返回所有标题为Document以及ID为1,2和3的译文的文档。
我可以使用条件创建2个不同的select,但是我无法在这些表之间生成内部联接来统一代码。
翻译条件查询
CriteriaQuery<Translation> translationQuery = builder.createQuery(Translation.class);
Root<Translation> translation = translationQuery.from(Translation.class);
List<Long> ids = new ArrayList<>();
ids.add(1);
ids.add(2);
ids.add(3);
Predicate idPredicate = translation.in(ids);
translationQuery.where(idPredicate);
translationQuery.distinct(true);
TypedQuery<Translation> query =
this.entityManager.createQuery(translationQuery);
query.getResultList();
返回ID为1,2和3的所有译文;
文档标准查询
CriteriaQuery<Document> documentQuery = builder.createQuery(Document.class);
Root<Document> document = documentQuery.from(Document.class);
Predicate titlePredicate = builder.like(document.get("title"), "%Document%");
documentQuery.where(titlePredicate);
TypedQuery<Document> query = this.entityManager.createQuery(documentQuery);
query.getResultList();
返回所有标题为“文档”的文档。
有提示吗?谢谢。
答案 0 :(得分:0)
经过大量的搜索,我使此解决方案统一了两个查询并使用内部联接:
//query creation
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<Document> documentQuery = builder.createQuery(Document.class);
Root<Document> root = documentQuery.from(Document.class);
//parameter list for where
List<Predicate> predicateList = new ArrayList<Predicate>();
//doing the join: pass the translations reference (list <Translations) that exists in the document model.
Join<Document, Translation> documentTranslationJoin = root.join("translations");
//I get the ids of the languages associated with the translations found in the join
Path<Long> translationLanguageId = documentTranslationJoin.get("language");
//I passed the ids of the languages that I want to find translations
List<Long> ids = new ArrayList<>();
ids.add(1);
ids.add(2);
ids.add(3);
//considers languages of translations
Predicate predicateTranslationId = builder.isTrue(translationLanguageId.in(ids));
//I passed the ids of the languages that will be the where looking for the translations that have the ids of the languages that I want to see
predicateList.add(predicateTranslationId);
//considers title of document
Predicate titlePredicate = builder.like(root.get("title"),"%documento%");
predicateList.add(titlePredicate);
//where
Predicate[] predicates = new Predicate[predicateList.size()];
predicateList.toArray(predicates);
documentQuery.where(predicates);
//execution of the query with its parameters
TypedQuery<Document> query = this.entityManager.createQuery(documentQuery);
query.setFirstResult(0);
query.setMaxResults(8);
//results
List<Document> documents = query.getResultList();