我在查询 GAE 数据存储时发现了奇怪的行为。在某些情况下,过滤器不适用于整数字段。以下 java 代码重现了该问题:
log.info("start experiment");
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
int val = 777;
// create and store the first entity.
Entity testEntity1 = new Entity(KeyFactory.createKey("Test", "entity1"));
Object value = new Integer(val);
testEntity1.setProperty("field", value);
datastore.put(testEntity1);
// create the second entity by using BeanUtils.
Test test2 = new Test(); // just a regular bean with an int field
test2.setField(val);
Entity testEntity2 = new Entity(KeyFactory.createKey("Test", "entity2"));
Map<String, Object> description = BeanUtilsBean.getInstance().describe(test2);
for(Entry<String,Object> entry:description.entrySet()){
testEntity2.setProperty(entry.getKey(), entry.getValue());
}
datastore.put(testEntity2);
// now try to retrieve the entities from the database...
Filter equalFilter = new FilterPredicate("field", FilterOperator.EQUAL, val);
Query q = new Query("Test").setFilter(equalFilter);
Iterator<Entity> iter = datastore.prepare(q).asIterator();
while (iter.hasNext()) {
log.info("found entity: " + iter.next().getKey());
}
log.info("experiment finished");
日志如下所示:
INFO: start experiment
INFO: found entity: Test("entity1")
INFO: experiment finished
出于某种原因,即使两个实体实际上都存储在数据存储中并且两个“字段”值都是 777(我在数据存储查看器中看到),它也只能找到第一个实体!为什么实体的创建方式很重要?我想使用 BeanUtils,因为它很方便。
本地开发服务器和部署到 GAE 时也会出现同样的问题。