DavidB
DavidB

Reputation: 2234

GAE datastore queries sometimes not working after changing entity

I'm trying to figure out an issue that I'm seeing. I'm noticing that when I change an entity object definition by adding a new field for instance, sometimes I no longer can get results from previous records that already exist in the datastore. For instance, in this example below, I can see the entity in the datastore, but I'm getting this exception:

SEVERE: No results for query: SELECT FROM com.alero.services.model.MyEntity myEntity WHERE myEntity.key = :key

I'm using JPA with the GAE datastore.

The only way I seem to be able to correct the problem and start getting results again is to delete the appengine-generated directory and then recreate the entities. Is it being cached in some manner and is there something I should be doing to allow the datastore to know that it needs to remove the cache if this is the case?

        String queryString = "select from " + MyEntity.class.getName()
                + " myentity where myentity.key = :key";

        Key keySub = KeyFactory.createKey("MyEntity", myEntityId);

        Query query = em.createQuery(queryString);
        query.setParameter("key", KeyFactory.keyToString(keySub));

        try {
            MyEntity myEntity = (MyEntity) query.getSingleResult();
            em.close();
            return myEntity;
        } catch (Exception e) {         
            log.severe(e.getMessage());
            em.close();
        }

Upvotes: 0

Views: 131

Answers (1)

DavidB
DavidB

Reputation: 2234

Actually I discovered the issue. It wasn't really related to me changing my entity. It was how I was persisting and merging my entities. I have an unowned relationship between two entities in an unowned bidirectional relationship and I was adding the references to each other before persisting my entities. This was creating an owned relationship. Therefore when I was querying with my key, I wasn't finding it because the actual key on the entity was a child key when I was trying to query it as a parent key.

So I need to persist my two entities before adding the relationships to each other in the bidirectional relationship. Then I can merge them. This creates a parent key for each entity and then I can create my relationship between the bidirectional relationship.

Upvotes: 1

Related Questions