Tadas Davidsonas Tadas Davidsonas - 27 days ago 4
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);
return "OK";

Trying delete the specific entity like this:

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

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


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)
    if (results.isEmpty())
        return "Not Found!";

    return "OK";