有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

使用Objectify在Google CloudDatastore中使用java findRecord

我想使用Objectify查询Google云数据存储。基于已知的键值对查找记录的合适方法是什么?记录在数据库中,我通过谷歌的数据存储查看器验证了这一点

这是我的方法存根,它触发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;
}

以下是用户类:

@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;
}
}

共 (2) 个答案

  1. # 1 楼答案

    首先在字段模型中添加@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();
    
  2. # 2 楼答案

    我认为它失败是因为交易。你需要打一个无转接电话,比如:

    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

    编辑 你的对象需要@Index注释。它会将字段添加到数据存储索引中。只能搜索索引中的属性。过滤法就是其中之一

    @Id
    Long id;
    @Index
    private HealthVault healthVault;
    @Index
    private String googleId;
    

    另外,用谷歌ID jochen删除你的对象。bauer@gmail.com并在更新实体后将其再次写入数据库。而客观化会找到它