Search code examples
javagoogle-app-engineresteasyobjectify

How to Update an Entity in a Google app engine data store partially


I am using Objectify in Google App Engine for Data Store. I am having an Entity with 6 Properties. For Example,

  • Key (id)

  • FirstName

  • LastName

  • Age

  • mobile_Number

  • Email

    I need to write an Update Endpoint for the Entity. I want that update Endpoint should be able to update the Entity with the specified fields Not the Entire Entity. For Example If I want to update the mobile_number, it should update the mobile number alone. or If i want to update the firstName it should update that only.

For that I need to write a common method to update the Entity based on the fields.

Many thanks in Advance!


Solution

  • Yes i fixed this update in the following way.

    Got the input parameter as Hashmap where i can get the user's properties that to be updated. The hashmap's key should be same as Entity's property value.

    public Response update(HashMap<String, String> ProfileEntity) {
     //update logic
    }
    

    and updated the value based on the following if condition:

            ProfileEntity existingEntity = getById(ProfileEntity.get("key"));
    
            if(existingEntity == null)
                System.out.println("Invalid Profile Key");
    
            if(ProfileEntity.containsKey("firstName"))
                existingEntity.setFirstName(ProfileEntity.get("firstName"));
    
            if(ProfileEntity.containsKey("lastName"))
                existingEntity.setLastName(ProfileEntity.get("lastName"));
    
            if(ProfileEntity.containsKey("age"))
                existingEntity.setAge(ProfileEntity.get("age")));
    
            if(ProfileEntity.containsKey("mobile_Number"))
                existingEntity.setMobileNumber(ProfileEntity.get("mobile_Number"));
    
            super.save(existingEntity);