如何动态构建多个参数的JDO查询 [英] How to dynamically build JDO Queries on multiple parameters
问题描述
//指定您的持久化实体查询并过滤使用参数
query = pm.newQuery(MyClass.class,customer == paramCustomer&& date> = paramStartDate&& date< = paramEndDate);
//声明
之上使用的参数query.declareParameters(com.google.appengine.api.users.User paramCustomer,java.util.Date paramStartDate,java.util.Date paramEndDate );
//传递声明为params的对象
MyClassList =(List< MyClass>)query.execute(user,startDate,endDate);
使用过滤器以编程方式构建字符串很简单:
customer == paramCustomer&& date> = paramStartDate&& date< = paramEndDate
和另一个与params声明一致:
com.google.appengine.api.users.User paramCustomer,java.util.Date paramStartDate,java.util.Date paramEndDate
不直接的是提出一个执行查询的策略,这取决于哪些参数在过滤器中(并且已被声明),所以最终会产生一些非常难看且特别的级联if-else语句包含所有可能的查询执行排列(所有参数,只有第一个,只有第二个,第一个和第二个等等):
MyClassList =(List< MyClass>)query.execute(user,startDate,endDate);
我相信这是一项常见任务,而其他人正在以更一般和有效的方式。
有什么建议吗?
通过这种方式,我可以动态构建过滤器和参数声明,将实际对象加载到对象数组中,然后传递给上述方法。 p>
另一个重要的方法是 executeWithMap
,您可以使用它来按名称绑定参数。
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.
这篇关于如何动态构建多个参数的JDO查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!