How to dynamically build JDO Queries on multiple parameters

有些话、适合烂在心里 提交于 2019-12-06 04:16:02

问题


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?


回答1:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!