开发者

How to build JPQL queries when parameters are dynamic?

开发者 https://www.devze.com 2023-04-03 06:10 出处:网络
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.

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?


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


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)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号