How to build JPQL queries when parameters are dyna

2019-07-12 16:48发布

问题:

I wonder if there is a good solution to build a JPQL query (my query is too "expressive" and i cannot use Criteria) based on a filter.

Something like:

query = "Select from Ent"
if(parameter!=null){
   query += "WHERE field=:parameter"
}
if(parameter2!=null) {
   query += "WHERE field2=:parameter2"
}

But i would write WHERE twice!! and the casuistic explodes as the number of parameter increases. Because none or all could be null eventually.

Any hint to build these queries based on filters on a proper way?

回答1:

Why can't you use a criteria, like this.

Other options (less good imho):

Create two named queries one for each condition, then call the respective query.

Or build up a string and use a native query.

Oh, do you just mean the string formation(?) :

query = "Select from Ent where 1=1 "
if(parameter!=null){
   query += " and field=:parameter"
}
if(parameter2!=null) {
   query += " and field2=:parameter2"
}

(I think that string formation is ugly, but it seemed to be what was asked for)



回答2:

select * from Ent    
    where (field1 = :parameter1 or :parameter1 is null)       
    and (field2 = :parameter2 or :parameter2 is null)