0
votes

I am trying to store the data in the Google App Engine Datastore after checking if the mobile number exists, but the code always shows "failure" even if the mobile number is in the database. It shows failure but still stores the data in Datastore.

Please check the code here and let me know what is my mistake:

String name= request.getParameter("name");
String email=request.getParameter("email");
String mobileno= request.getParameter("mobileno");
String password= request.getParameter("passwd");
String status=""; 
//
Query query = new Query("dailyquizuser");
    query.addFilter("mobileno", Query.FilterOperator.EQUAL, mobileno);
     DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
    PreparedQuery pq = datastore.prepare(query);
    Entity dailyquizuserentity = pq.asSingleEntity();

    out.println("dailyquizuserentity: " + dailyquizuserentity);
    if(dailyquizuserentity != null){
        status="failure";
        out.println(status);


    } else {
        Key dailyquizuserKey = KeyFactory.createKey("dailyquizuser", "dailyquiz");
        Entity  dailyquizuser = new Entity("dailyquizuser", dailyquizuserKey);
        dailyquizuser.setProperty("name",  name);
        dailyquizuser.setProperty("email", email);
        dailyquizuser.setProperty("mobileno", mobileno);
        dailyquizuser.setProperty("password", password);

       DatastoreService datastore1 = DatastoreServiceFactory.getDatastoreService();
        datastore1.put(dailyquizuser);
        out.println("dailyquizuser: " + dailyquizuser);
        status="success";
        out.println(status);

    }


    %> 
1

1 Answers

0
votes

A few notes:

  1. You should check that mobileno variable is not null (same with all other required parameters). This would explain why you always find an entity - null is a valid property value. Querying with null filter will find an entity that has null property, but querying for an entity with no property will not find it.

  2. The code you showed creates entities with a single parent:

    // a key to a parent
    Key dailyquizuserKey = KeyFactory.createKey("dailyquizuser", "dailyquiz"); 
    
    // new entity with a parent
    Entity  dailyquizuser = new Entity("dailyquizuser", dailyquizuserKey); 
    

    So when searching for 'dailyquizuser' you should consider using ancestor query.

  3. addQuery(..) is deprecated. Use setQuery() instead.