jpa多表联查动态,JPA查询的动态参数数量

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 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.)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值