我在使用Google Cloud Datastore时遇到了问题。到目前为止,除了UPDATE方法之外,我设法使一切正常工作......每当我想要更新现有实体时,它会创建一个新实体而不是更新旧实体。我很肯定我给出了正确的身份证,但现在我真的没有想法。我搜索了类似的问题并找到了一些:
但无法解决我的问题。我现在正在使用生成的端点。
这是我的代码:
型号:
@Entity
public class Address implements Serializable {
@Id
private Long id;
private String street;
private String street_nr;
private String city;
private String zip;
private String country;
public Address(){ }
public Long getKey(){
return id;
}
public String getStreet() {
return street == null ? "" : street;
}
public void setStreet( String street) {
this.street = street;
}
public String getStreetNr() {
return street_nr == null ? "" : street_nr;
}
public void setStreetNr( String streetNr) {
this.street_nr = streetNr;
}
public String getCity() {
return city == null ? "" : city;
}
public void setCity( String city) {
this.city = city;
}
public String getZip() {
return zip == null ? "" : zip;
}
public void setZip( String zip) {
this.zip = zip;
}
public String getCountry() {
return country == null ? "" : country;
}
public void setCountry(String country) {
this.country = country;
}
}
端点:
@ApiMethod(
name = "update",
path = "address/{id}",
httpMethod = ApiMethod.HttpMethod.PUT)
public Address update(@Named("id") Long id, Address address) throws NotFoundException {
checkExists(id);
ofy().save().entity(address).now();
logger.info("Updated Address: " + address);
return ofy().load().entity(address).now();
}
private void checkExists(Long id) throws NotFoundException {
try {
ofy().load().type(Address.class).id(id).safe();
} catch (com.googlecode.objectify.NotFoundException e) {
throw new NotFoundException("Could not find Address with ID: " + id);
}
}
我的服务器日志告诉我地址已更新。因此,我假设checkExists(id)按预期工作。
com.PACKAGE.AddressEndpoint更新:更新地址:com.PACKAGE.models.Address@495871
助手:
public static AddressApi getEndpoints() {
// Create API handler
final AddressApi.Builder builder = new AddressApi.Builder(
AndroidHttp.newCompatibleTransport(),
new AndroidJsonFactory(), null)
.setRootUrl(Constants.ROOT_URL)
.setApplicationName(Constants.APPLICATION_NAME);
return builder.build();
}
最后是电话:
Address address = AddressBuilderHelper.getEndpoints().get(MY_KEY).execute();
address.setCity("San Francisco");
AddressBuilderHelper.getEndpoints().update(address.getKey(), address).execute();
然后就像插入一样创建一个新的实体。我在这里没有想法:(
感谢您的帮助。我真的很感激。
更新
原来唯一缺少的是id属性的setter。添加它就完成了工作!