MasterJay
MasterJay

Reputation: 33

What is the difference below?

I would like to find out what is the difference between the code line below in terms of Keys.

 Entity e = new Entity("Employee", 100);

And

 Key k = KeyFactory.createKey("Employee", 100);
 Entity e = new Entity("Employee", k);

Upvotes: 1

Views: 39

Answers (1)

David
David

Reputation: 5519

Short version

The first line creates an Employee entity of id 100 whereas the second one creates an Employee entity that is a child of the entity created in the first line.

More details

Entity e = new Entity("Employee", 100);

This line creates a new entity of kind Employee and with an id of 100.

Key k = KeyFactory.createKey("Employee", 100);
Entity e = new Entity("Employee", k);

Those lines do the following :

  1. Create a key referencing the entity of kind Employee and the id 100. This key could be used to reference the entity created by the first line of code you shared.
  2. Create an entity of type Employee who has for ancestor the entity referenced by the key created before. The new entity also has an id, but since you did not specify it in the constructor, it will be a long generated by App Engine when the entity is saved into the datastore.

If you're unsure about the concept of ancestors, checkout out this documentation page.

Upvotes: 3

Related Questions