JPA 2.0 dynamic query using criteria API

I am a little fixated on building a dynamic query using CriteriaBuilder JPA 2.0.

I have a fairly common case, I suppose: The user provides an arbitrary number of X search parameters that must be and / or concatenated: for example:

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

The Builder method or criterion is not dynamic:

Predicate or (Predicate ... restrictions)

Ideas? Samples?

+9
java dynamic jpa criteria-api
Mar 24 '10 at 17:45
source share
2 answers

In your case, I would prefer to use Expression#in(Collection) to avoid the need to loop and create a Predicate connection 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)); 

For more information, you can check the Basic types of secure queries using the criteria API and metamodel API .

+7
Mar 25 '10 at 12:09
source share

in this code, Foo_.name will give a compilation error. Since the field is not declared in this. I can’t figure it out. Please suggest me.

-raghu

+1
Aug 03 '10 at 8:07
source share



All Articles