Dynamic JPA 2.0 query using Criteria API

依然范特西╮ 提交于 2019-12-18 15:34:19

问题


I am a bit stucked constructing a dynamic query using the CriteriaBuilder of JPA 2.0.

I have quite a common use case I guess: User supplies a arbitrary amount of search parameters X to be and / or concatenated: like :

select e from Foo where (name = X1 or name = X2 .. or name = Xn )

The Method or of CriteriaBuilder is not dynamic:

Predicate or(Predicate... restrictions)

Ideas? Samples?


回答1:


In your case, I would rather use Expression#in(Collection) to avoid having to loop and to build a compound Predicate dynamically:

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.




回答2:


in this code Foo_.name is going to give compilation error. As the field is not declared in that. I'm not able to understand this. Please suggest me.

-raghu



来源:https://stackoverflow.com/questions/2510106/dynamic-jpa-2-0-query-using-criteria-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!