App Engine数据存储 - 枚举字段查询

6

I am using GAE(Java) with JDO for persistence.

I have an entity with a Enum field which is marked as @Persistent and gets saved correctly into the datastore (As observed from the Datastore viewer in Development Console). But when I query these entities putting a filter based on the Enum value, it is always returning me all the entities whatever value I specify for the enum field.

I know GAE java supports enums being persisted just like basic datatypes. But does it also allow retrieving/querying based on them? Google search could not point me to any such example code.

Details:

I have printed the Query just before being executed. So in two cases the query looks like -

SELECT FROM com.xxx.yyy.User WHERE role == super ORDER BY key desc RANGE 0,50

SELECT FROM com.xxx.yyy.User WHERE role == admin ORDER BY key desc RANGE 0,50

Both above queries return me all the User entities from datastore in spite of datastore viewer showing some Users are of type 'admin' and some are of type 'super'.

3个回答

3

如果要声明的参数不是字符串或整数类型,我认为您需要使用 declareParameters。请尝试以下代码:

Query q = pm.newQuery(com.xxx.yyy.User.class);
q.setFilter("role == p1");  //p1 is a variable place holder
q.declareParameters("Enum p1"); //here you define the data type for the variable, in this case an Enum
q.setRange(0, 50);
q.setOrdering("key desc");

AbstractQueryResult results = (AbstractQueryResult) pm.newQuery(q).execute(admin);

或者,如果您想要更多类似GQL的语法 -
Query query = pm.newQuery("SELECT FROM com.xxx.yyy.User WHERE role == p1 ORDER BY key desc RANGE 0,50");
query.declareParameters("Enum p1");
AbstractQueryResult results = (AbstractQueryResult) pm.newQuery(q).execute(admin);

你在发布之前试过这个吗?在我尝试了所有可能的方法之前,我不会向谷歌报告错误。 - Gopi
嗯,我知道这已经过去一年了,但我刚遇到了这个问题,而且这个答案对我很有用。 - matt burns

3

2

在声明查询参数时,您需要使用枚举类名称。

例如,如果您使用方法样式构建查询,并假设您的枚举称为Role并在User类下声明,则可以执行以下操作:

Query query = pm.newQuery(com.xxx.yyy.User.class);
query.setFilter("role == roleParam");
query.declareParameters(com.xxx.yyy.User.Role.class.getName() + " roleParam");

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接