[英]Dynamic JPA 2.0 query using Criteria API
I am a bit stucked constructing a dynamic query using the CriteriaBuilder of JPA 2.0. 我使用JPA 2.0的CriteriaBuilder构建动态查询有点困难。
I have quite a common use case I guess: User supplies a arbitrary amount of search parameters X to be and / or concatenated: like : 我猜有一个很常见的用例:用户提供任意数量的搜索参数X和/或连接:如:
select e from Foo where (name = X1 or name = X2 .. or name = Xn )
The Method or of CriteriaBuilder is not dynamic: 方法或CriteriaBuilder不是动态的:
Predicate or(Predicate... restrictions) 谓词或(谓词......限制)
Ideas? 想法? Samples?
样品?
In your case, I would rather use Expression#in(Collection)
to avoid having to loop and to build a compound Predicate
dynamically: 在您的情况下,我宁愿
Expression#in(Collection)
使用Expression#in(Collection)
来避免循环并动态构建复合Predicate
:
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Foo> cq = cb.createQuery(Foo.class);
Metamodel m = em.getMetamodel();
EntityType<Foo> Foo_ = m.entity(Foo.class);
Root<Foo> foo = cq.from(Foo_);
cq.where(my.get(Foo_.name).in(params));
You might want to check Basic Type-Safe Queries Using the Criteria API and Metamodel API for more details. 您可能需要使用Criteria API和Metamodel API检查基本类型安全查询以获取更多详细信息。
in this code Foo_.name is going to give compilation error. 在此代码中,Foo_.name将提供编译错误。 As the field is not declared in that.
由于该领域未在此声明。 I'm not able to understand this.
我无法理解这一点。 Please suggest me.
请建议我。
-raghu -raghu
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.