如何在参数动态时构建JPQL查询? [英] How to build JPQL queries when parameters are dynamic?

查看:398
本文介绍了如何在参数动态时构建JPQL查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道是否有一个很好的解决方案来构建一个JPQL查询(我的查询太表现力,我不能使用Criteria)基于过滤器。



例如:

  query =从Ent中选择
if(parameter!= null){
查询+ =WHERE field =:参数

if(parameter2!= null){
query + =WHERE field2 =:parameter2
}

但我会写两次!随着参数数量的增加,casuistic会爆炸。

任何提示以正确的方式基于过滤器构建这些查询?

解决方案

为什么你不能使用标准这样



其他选项(不太好的imho):

创建两个为每个条件命名查询,然后调用相应的查询。



或者建立一个字符串并使用本地查询



哦,你的意思是字符串形式(?):

  query =Select from 1 where 1 = 1
if(parameter!= null){
query + =and field = :参数

if(parameter2!= null){
query + =and f ield2 =:parameter2

(我认为字符串的形成很丑陋,但它似乎是被要求的)


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?

解决方案

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)

这篇关于如何在参数动态时构建JPQL查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆