Dynamic JPA 2.0 query using Criteria API
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 f开发者_StackOverflow中文版rom Foo where (name = X1 or name = X2 .. or name = Xn )
The Method or of CriteriaBuilder is not dynamic:
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:
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.
精彩评论