JPA Criteria API-如何选择“字段不在" [英] JPA Criteria API - how to select like "field not in"

查看:146
本文介绍了JPA Criteria API-如何选择“字段不在"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下情况.

public class TestExecution {

    private Collection<TestExecutionTag> testExecutionTags;

}


public class TestExecutionTag {


    private Tag tag;

}


public class Tag {

    private String name;

}

我现在想要做的是使用标准的JPA Criteria API执行以下查询,例如:

What I now want to do is to perform following query using standard JPA Criteria API, something like:

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>).

这样可能吗?

编辑:很抱歉,我没有正确指定,因为我认为这无关紧要.整个目标实际上是选择带有特定标签的测试执行,但从其中排除那些包含其他标签的执行.

I'm sorry I didn't specify it correctly, since I thought it's irrelevant. The whole goal was actually to select test executions with specific tags but from them exclude those which contain other tags.

推荐答案

我终于得到了答案,但是非常感谢@Priyesh评论和以下链接:

I finally got the answer but thanks a lot to @Priyesh comment and this link: "Not in" constraint using JPA criteria

编辑后,我意识到它的目标几乎没有什么不同(请参见编辑后的帖子).

After edit I realized that it the goal is little different (see the edited post).

因此必须使用子查询,请参见: JPQL,如何不选择某些内容

So Subquery had to be used, see: JPQL, How to NOT select something

对任何人来说,这都是对我有用的Criteria API查询,但基本上只是上面重写的JPQL查询.

Just for anybody, here is the Criteria API Query that worked for me, but it's basically just rewritten JPQL query above.

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));

希望这对某人有帮助! :-)

Hope that this helps somebody! :-)

这篇关于JPA Criteria API-如何选择“字段不在"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆