我想使用Objectify来查询Google Cloud Datastore。根据已知的键值对查找记录的合适方法是什么?记录在数据库中,我通过Google的Datastore查看器验证了这一点。
下面是我的方法存根,它触发了NotFoundException:
@ApiMethod(name="getUser")
public User getUser() throws NotFoundException {
String filterKey = "googleId";
String filterVal = "jochen.bauer@gmail.com";
User user = OfyService.ofy().load().type(User.class).filter(filterKey, filterVal).first().now();
if (user == null) {
throw new NotFoundException("User Record does not exist");
}
return user;
}下面是User类:
@Entity
public class User {
@Id
Long id;
private HealthVault healthVault;
private String googleId;
public User(String googleId){
this.googleId = googleId;
this.healthVault = new HealthVault();
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public HealthVault getHealthVault() {
return healthVault;
}
public void setHealthVault(HealthVault healthVault) {
this.healthVault = healthVault;
}
public String getGoogleId() {
return googleId;
}
public void setGoogleId(String googleId) {
this.googleId = googleId;
}
}发布于 2016-08-25 17:47:21
我认为它失败是因为事务。您需要进行一个无限制呼叫,如下所示:
User user = OfyService.ofy().transactionless().load().type(User.class).filter(filterKey, filterVal).first().now();有关App Engine上事务的更多信息:https://cloud.google.com/appengine/docs/java/datastore/transactions https://github.com/objectify/objectify/wiki/Transactions
编辑你的对象需要@索引注解。它会将字段添加到数据存储索引。只有索引中的属性才是可搜索的。Filter方法就是其中之一。
@Id
Long id;
@Index
private HealthVault healthVault;
@Index
private String googleId;附注:使用googleId jochen.bauer@gmail.com删除您的对象,并在更新实体后将其再次写入数据库。而objectify将会找到它。
发布于 2016-08-25 22:39:43
首先,在您的字段模型中添加@Index。在你的模型中,我没有把filterVal看作一封电子邮件。即便如此,要在你的filterVal中获取实体,假设googleId是你的实体的字段。
User user = OfyService.ofy().load().type(User.class).filter("googleId", filterVal).now();所以如果你的filterKey是你的实体的id。
User user = OfyService.ofy().load().key(Key.create(User.class, filterKey)).now();https://stackoverflow.com/questions/39138403
复制相似问题