One can easily use JDO syntax to query on multiple parameters as follows:
//specify the persistent entity you're querying and you filter usign params
query = pm.newQuery(MyClass.class, " customer == paramCustomer && date >= paramStartDate && date <=paramEndDate ");
// declare params used above
query.declareParameters("com.google.appengine.api.users.User paramCustomer, java.util.Date paramStartDate, java.util.Date paramEndDate");
//pass the object declared as params
MyClassList = (List<MyClass>) query.execute(user, startDate, endDate);
It's straightforward to programmatically build a string with the filter:
"customer == paramCustomer && date >= paramStartDate && date <=paramEndDate"
and another strign with the params declaration:
"com.google.appengine.api.users.User paramCustomer, java.util.Date paramStartDate, java.util.Date paramEndDate"
What's not immediate is to come up with a strategy for executing the query depending on which params are in the filter (and have been declared), so you end up with a number of really ugly and ad-hoc cascading if-else statements with all the possible permutations of the query execution (all the params, only the first, only the second, first and second etc...):
MyClassList = (List<MyClass>) query.execute(user, startDate, endDate);
I am sure this is a common task and someone else is doing it in a more general and efficient way.
Any suggestion?
I found a solution in the method query.executeWithArray
This way I can build filters and param declaration dynamically an load up the actual objects into an array of object which is then passed to the method mentioned above.
Another important method is executeWithMap
wich you can use to bind parameters by name.
来源:https://stackoverflow.com/questions/935762/how-to-dynamically-build-jdo-queries-on-multiple-parameters