簡體   English   中英

JPA Criteria API-如何選擇“字段不在”

[英]JPA Criteria API - how to select like “field not in”

我有以下情況。

public class TestExecution {

    private Collection<TestExecutionTag> testExecutionTags;

}


public class TestExecutionTag {


    private Tag tag;

}


public class Tag {

    private String name;

}

我現在想做的是使用標准的JPA Criteria API執行以下查詢:

Select test executions (TestExecution) which don't have associated any of the tags (Tag) with name field value in provided list.

我會形容為

Select testExecution WHERE testExecution.testExecutionTag.tag.name NOT IN (<ArrayList of String values>).

這樣的事情可能嗎?

編輯:對不起,我沒有正確指定它,因為我認為這無關緊要。 總體目標實際上是選擇帶有特定標簽的測試執行,但從中排除包含其他標簽的測試。

我終於得到了答案,但非常感謝@Priyesh注釋和此鏈接: 使用JPA標准的“不參與”約束

編輯后,我意識到它的目標幾乎沒有什么不同(請參閱編輯后的帖子)。

因此必須使用子查詢,請參見: JPQL,如何不選擇某些內容

對於任何人來說,這都是對我有用的Criteria API查詢,但基本上只是上面重寫的JPQL查詢。

Predicate wantedToBePresentTags = cb.lower(rTag.<String>get("name")).in(cb.parameter(List.class, "tagList"));

Subquery sq = criteriaQuery.subquery(TestExecution.class);
Root sqRoot = sq.from(TestExecution.class);
Join<TestExecution, Tag> sqTag = sqRoot.joinCollection("testExecutionTags").join("tag");
sq.select(sqRoot.get("id"));
sq.where(cb.lower(sqTag.<String>get("name")).in(cb.parameter(List.class, "excludedTagList")));

Predicate excludedTags = cb.not(rExec.get("id").in(sq));

...
criteriaQuery.where(cb.and(wantedToBePresentTags, excludedTags));

希望對您有所幫助! :-)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM