简体   繁体   English

JPA - 带有“WHERE”子句的CriteriaQuery

[英]JPA - CriteriaQuery with “WHERE” clause

I know this can be a very simple question to some of u, but I'm having a hard time trying to find out how to build a simple Select * From X Where Xa = :myparam using a CriteriaBuilder . 我知道这对你们来说可能是一个非常简单的问题,但是我很难找到如何使用CriteriaBuilder构建一个简单的Select * From X Where Xa =:myparam

Now, this is the code I have managed to build so far: 现在,这是我到目前为止构建的代码:

    CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
    CriteriaQuery cq = cb.createQuery();

    Root<MyClass1> r = cq.from(MyClass1.class);
    cq.select(r);

    ParameterExpression<Long> p = cb.parameter(Long.class);

    cq.where(cb.equal(r.get("anotherClass.id"), p));

    javax.persistence.Query q = getEntityManager().createQuery(cq);

The class where I am applying this query is this one: 我应用此查询的类是这样的:

@Entity
public class MyClass1 implements Serializable {
    @Id
    private Long id;
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "ANOTHERCLASS_ID")    
    private AnotherClass anotherClass;
    ...
}

@Entity
public class AnotherClass implements Serializable {
    @Id
    private Long id;
    ...
}

I just need to select all records from myclass1 "WHERE" anotherClass.id = 1L , and where do I set the "1L", I know it goes in p but where? 我只需要从myclass1 “WHERE” anotherClass.id = 1L中选择所有记录,我在哪里设置“1L”,我知道它在p中但是在哪里?

That's all. 就这样。 Looks simple, but I am really not familiar with this CriteriaBuilder thing, so hope you can have some answers. 看起来很简单,但我真的不熟悉这个CriteriaBuilder的东西,所以希望你能得到一些答案。

Thanks. 谢谢。

Parameters are set in Criteria queries the same as in JPQL or native queries, you set them on the Query. Criteria查询中的参数与JPQL或本机查询中的相同,您可以在Query上设置它们。

ie

javax.persistence.Query q = getEntityManager().createQuery(cq);
q.setParameter(1, 1L);

Note that you are using a positional parameter, to use a named one pass the name to parameter(). 请注意,您正在使用位置参数,使用命名的参数将名称传递给parameter()。

ParameterExpression<Long> p = cb.parameter(Long.class, "id");
...
q.setParameter("id", 1L);

See, http://en.wikibooks.org/wiki/Java_Persistence/Querying#Parameters 参见http://en.wikibooks.org/wiki/Java_Persistence/Querying#Parameters

you are trying to use a joined table in a where clause expression, so you need to use a join between tghe tables first. 您正尝试在where子句表达式中使用连接表,因此您需要首先在tghe表之间使用连接。

...
Join<MyClass1,ANotherClass> pathA = r.join(MyClass.anotherClass);

...

cb.where(cb.equal(pathA.get(AnotherClass_.id), p));

Provided you have Metamodel classes built. 如果您已经构建了Metamodel类。 See also Chapter 40 of the Java EE Tutorial. 另请参阅Java EE教程的第40章。

Regards, Thomas 此致,托马斯

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM