Tadas Davidsonas Tadas Davidsonas - 1 year ago 86
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?

Answer Source

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";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download