richard
richard

Reputation: 854

storing and loading entities with objectify returns different results

i am learning to store and load data with objectify at the moment. i wrote following entity class:

@Entity
public class Contact {

    public Contact(){}

    @Id
    public Long id;
    public String name;

    public Contact(String name) {
        this.name = name;
    }
}

for testing i wrote a method that delete all entities of my type Contact which i saved before:

List<Key<Contact>> keys = ObjectifyService.ofy().load().type(Contact.class).keys().list();
ObjectifyService.ofy().delete().keys(keys).now();

and at the end of the method i create new entities of the same type again:

Contact contact1 = new Contact("name1");       
ObjectifyService.ofy().save().entity(contact1).now();
Contact contact2 = new Contact("name2");       
ObjectifyService.ofy().save().entity(contact2).now();
Contact contact3 = new Contact("name3");       
ObjectifyService.ofy().save().entity(contact3).now();
Contact contact4 = new Contact("name4");       
ObjectifyService.ofy().save().entity(contact4).now();
Contact contact5 = new Contact("name5");       
ObjectifyService.ofy().save().entity(contact5).now();

the strange thing about this is, that each time i rerun this code i get different numbers of results (varies from 3 - 5 returned Contact entities):

 List<Contact> contacts = ofy // loading the last created Contact entities
                .load()
                .type(Contact.class) 
                .list();
        size = contacts.size(); // size is sometimes 3, 4 or 5

so what should i change in order to get allways all of my 5 saved Contact entities back after i rerun the code?

Upvotes: 0

Views: 281

Answers (1)

Eric Simonton
Eric Simonton

Reputation: 6029

Because you are querying for the created objects immediately, the behavior you see is because of "eventual consistency." The objects are actually being created, there is just a delay before they are available. You can read more about eventual consistency and how to avoid it here. As a general rule, when you don't require strong consistency it is best to settle for eventual.

The local datastore in your development environment simulates eventual consistency for you. It is possible to adjust that, as documented here.

Upvotes: 1

Related Questions