Tadas Davidsonas Tadas Davidsonas - 2 months ago 14
Java Question

Trouble deleting entity with specific property set in Java GAE

I have the entities created like this:

public String addNewStockName(String newStock) throws DelistedException {
Entity stock = new Entity("Stocks");
stock.setProperty("Name", newStock);
ds.put(stock);
return "OK";
}


Trying delete the specific entity like this:

public String deleteStockName(String stockName){
Key key = KeyFactory.createKey("Stocks", stockName);
ds.delete(key);
return "OK";
}


And it does not delete the entity which has property 'stockName'. Why?

Answer

Your Stocks entity has a property named "Name". That is not the same as the key name.

You have to perform a query to get the entities or entity keys matching the filter of "Name=?".

Something like this:

public String deleteStockName(String stockName) {
    DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
    Filter f = new FilterPredicate("Name", FilterOperator.EQUAL, stockName);
    Query q = new Query("Stocks").setFilter(f).setKeysOnly();

    List<Entity> results = ds.prepare(q)
            .asList(FetchOptions.Builder.withDefaults());
    if (results.isEmpty())
        return "Not Found!";

    ds.delete(results.get(0).getKey());
    return "OK";
}
Comments