JPA查询的动态参数数量 [英] Dynamic number of parameters for a JPA query

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

问题描述

如何在运行时为JPA查询设置动态数量的参数?例如,我将JPA查询设置为

  String queryString =从项目x中选择x WHERE x.itemName =:name AND x.itemLocatio =:location; 
Query q = QueryFactory.createQuery(queryString);
q.setParameter(itemName,name);
q.setParamater(itemLocation,location);
列表<项目>结果= q.getResultList();

如果我只想传递itemName而不想过滤位置,我需要什么值然后设置位置?在我们可以选择不在运行时为一个或多个字段设置参数的情况下,如何进行这样的查询?我通过在运行时检查参数值来做到这一点,但由于查询字符串和参数设置是通过很多if检查创建的,所以代码变得太长。

/ div>

听起来好像你有正确的方法:你需要在运行时构造查询字符串,并包含你想要的元素。



但它不应该太麻烦:

  if(name!= null)
queryString + =AND x.itemName =:名称;
if(location!= null)
queryString + = ...

然后类似的设置参数。

(根据您的查询数据来源,您可能需要检查它们是否为非空,即检查!。equals(name)而不是 name!= null 。)


How can I have dynamic number of parameters for a JPA query at runtime?For example,I am having a JPA query set as

String queryString="Select x from Item x WHERE x.itemName=:name AND x.itemLocatio=:location";
Query q=QueryFactory.createQuery(queryString);
q.setParameter("itemName", name);
q.setParamater("itemLocation",location);
List<Item> result=q.getResultList();

What if I want to only pass itemName only and dont want to filter on location.what value i need to set for location then? How such kind of queries can be made where we can have option to not set parameter for one or more field at runtime? I have done this by checking parameter values at runtime but for that the code becomes too long as querystring and parameter setting are created through lots of if checks.

解决方案

It sounds as though you've got the right approach: you need to construct the query string at runtime, and include the elements you want.

It shouldn't be too cumbersome, though:

if (name!=null)
    queryString += " AND x.itemName=:name";
if (location!=null)
    queryString += ...

And then something similar for setting the parameters.

(Depending on your source of query data, you might want to check that they're non-empty, i.e., check !"".equals(name) rather than name!=null.)

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

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