Search code examples
objectify

How to stop Objectify from returning cached values?


I'm saving an object with Objectify like this:

Thing th = new Thing();
th.identifier = thingId;
th.name = thingName;
th.json = thingData;
ofy().save().entity(thing);
pResponse.setStatus(200);
pResponse.getWriter().println("OK");

I verify using the GAE datastore browser that the value has been updated in the database. I'm running locally. Then I load all things like this:

Map<String, List<Thing>> responseJsonMap = new HashMap<String, List<Thing>>();
List<Thing> things = ofy().load().type(Thing.class).list();         
responseJsonMap.put("things", things);
pResponse.setContentType("application/json");
try {
    GSON.toJson(responseJsonMap, pResponse.getWriter());
} ...

What I get back is the data that existed before the save. I have tried turning caching off on the entity and calling ofy().clear() but neither work. If I restart my server or wait long enough, the saved data comes through. I have also tried adding .now() after the save, but it's not necessary since I can verify in the datastore that the action has completed. I really would like to be able to load the data I just saved. What am I doing wrong?


Solution

  • What I'm doing wrong is not reading the manual and forgetting a step.

    Objectify requires a filter to clean up any thread-local transaction contexts and pending asynchronous operations that remain at the end of a request. Add this to your WEB-INF/web.xml:

    <filter>
         <filter-name>ObjectifyFilter</filter-name>
         <filter-class>com.googlecode.objectify.ObjectifyFilter</filter-class>
    </filter>
    <filter-mapping>
         <filter-name>ObjectifyFilter</filter-name>
         <url-pattern>/*</url-pattern> 
    </filter-mapping>
    

    Well, good thing to check if you're getting cached values that you really don't expect.