GAE: Tutorial: Code Lab Exercise 1: Working with Entities

Goal

This tutorial guides you through the process of creating a sample application to perform CRUD operations on entities. These entities are stored and retrieved using the DataStore APIs from datastore defined by GAE.

For this exercise we will build a sample product catalog with two entities: Product and Item. The application provides UI to perform all the CRUD operations on the entities.

Following actions will be covered in this exercise:

  1. Create entities of type product, item
  2. List entity details
  3. Edit entity details
  4. Delete entity

Time for completion

Approximately 30 minutes.

Prerequisites

Before you begin this tutorial, you should be familiar with:

  • Web application basics and deployment process
  • Servlet basics
  • Knowledge on XML-HTTP request
  • Working with Eclipse IDE

Index

This tutorial is organized into the following sections:

Code lab overview

  1. Code lab exercise is a web application template. The idea of the template based sample is to get hands-on experience with Google App Engine concepts. This exercise will cover all the steps required to create, deploy and monitor application on GAE environment.

  1. The picture shows a solution overview. Goal of this exercise is to demonstrate the GoogleDataStore service API for persisting data

    In this exercise we will create the Product and Item entities, store and retrieve them. The datastore is the service provided by the App Engine. UI is built using HTML and javascript and data from the application is sent to browser in JSON format.

    The use of memcache is demonstrated in the next exercise.

Setup : Import Code Lab Exercise 1

  1. Import the source code from the downloaded folder CodeLabEx1-starter as follows. Select File > Import from Eclipse IDE and select CodeLabEx1-starter folder.

Working with the exercise

The App Engine provides a robust and scalable Datastore for storing, searching and retrieving data. The App Engine datastore saves data objects as entities. An entity has one or more properties, named values of one of several supported data types for instance a string, an integer, or even a reference to another entity.

About Entity

An entity is an object representation of a datastore row. Unlike a row in a relational database, there are no predefined columns. There are no tables corresponding to types of data.

Entities don’t have columns – they have properties. A property represents a field of your entity. For instance, a person entity would have a kind of person, a key corresponding to a unique identifier corresponding to their name. The Kind of the entity is stored as part of the entity key. Entity Key is the primary way by which entities are fetched, even when the queries are issued. It’s similar to a primary key in an RDBMS. The key encodes your application ID, your entity’s kind, any parent entities and other metadata. The entity ID can also be a string that can be provided by the application.

This exercise shows how to create and retrieve entries to and from a data store. Each entity also has a key that uniquely identifies the entity. The simplest way is to have the Kind and Entity ID provided by the datastore. Kind indexes the entity and helps in querying the datastore efficiently.

Getting the Handle to DataStoreService

Take a look at the com.google.appengine.codelab.Util class. The Util class has all the methods to store and retrieve entities from the datastore. It is wrapper for DatastoreService provided by the App Engine api.

Edit the Util class as follows. Locate the following line of code in the Util class.

private static DatastoreService datastore = null;

Replace the above line with the code below.

private static DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
  • The getDatastoreService() method of DatastoreServiceFactory returns DataStoreService that an application can use. The DatastoreService has put()get() and delete() methods. There is no need to worry about opening or closing service.
  • persistEntity() method saves the entity using the datastore service put() API.
  • deleteEntity() method deletes the entiry using the datastore service delete() API.
  • findEntity() method searches the datastore given a key usign the datastore service find() API.
  • listEntities() methods allows to search by adding filters through Query class. Executes the query using prepare. Prepare also returns an iterator.
  • writeJSON() method is an utility method to send back the servlet response as JSON to the browser.
  1. Creating OR Updating Item Entity

    The code demonstrates creation of entities.
    An entity can be created with an app-assigned key name (in this case, name) string or a system-assigned numeric ID as its identifier to create the object. To set a key name, provide it as the second argument to the Entity constructor. Simply omit the argument, to indicate that the datastore should assign a unique numeric ID automatically.

    Entity does not contain setKey() or setKind() methods. This is because an entity’s key is immutable. Once an Entity has a key, it can never be changed.

    Locate the createOrUpdateItem() method in com.google.appengine.codelab.Item and insert the following lines of code.
    Make sure to return item instead of null.

    Entity product = Product.getProduct(productName);
    Entity item = getSingleItem(itemName);
    if(item == null){
      item = new Entity("Item",product.getKey());
      item.setProperty("name", itemName);
      item.setProperty("product", productName);
      item.setProperty("price", price);
    } else{
      if (price != null && !"".equals(price)) {
        item.setProperty("price", price);
      }          
    }
    Util.persistEntity(item);
    return item;

    util.persistEntity() invokes the DatastoreService’s put() to persist the Entity.
    The product’s name is used as key. The same key is used to retrieve the product later.

  2. Deleting Item Entity

    An Entity can be deleted using deleteItem() method in Item class. Add the below code to deleteItem() method.

    Entity entity = getSingleItem(itemKey);    
    if(entity != null){
      Util.deleteEntity(entity.getKey());
      return("Item deleted successfully.");
    } else
      return("Item not found");

    Util.deleteEntity() invokes the DatastoreService’s delete() to delete the Entity.

  3. Finding Item Entity

    To search an entity, use findEntity() method of Util.java . Add the below code to getSingleItem() method of Item class.
    Ensure the found Entity is returned.

    Query query = new Query("Item");
    query.addFilter("name", FilterOperator.EQUAL, itemName);
    List<Entity> results = Util.getDatastoreServiceInstance().prepare(query).asList(FetchOptions.Builder.withDefaults());
    if (!results.isEmpty()) {
      return (Entity)results.remove(0);
    }
    return null;

Run the Application

    Refer Appendix A 

  1. Once the application is deployed locally, open a browser and access the following URLhttp://localhost:8888/

    The welcome screen is shown below.

  2. Click on “Add” button from top panel. Make sure you are on Product tab.Fill in the create form and click on “Save” button

  3. On saving the product, the product list view appears
  4. Click “Add” button from the top panel. Make sure you are on Create Item tab.Fill the form, select the product type and then click on “Save” button.

  5. On saving the Item, the Item list view appears
  6. To update an item, Click on “Edit” which shows the below screen.
  7. To verify the entity creation, check for newly created item in the item listing.In next section, we can see the admin console and verify the data entities created.

Admin Console

  1. Login to ‘Admin Console’ to verify the entity present in the data store.Admin console can be opened on development machine using http://localhost:8888/_ah/admin

    Click on DataStore Viewer –> Select Item from Entity Kind list and click List Entities to view the product created.

Deploy your application to GAE

  1. Refer Appendix B

Summary

  1. Congratulations! You’ve completed the code lab exercise.You can also see the solution to the exercise in folder CodeLabEx1 folder.