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