Search code examples
google-app-enginememcachedjdotransient

Determine if object belongs to persistence manager or not


My specific question (everything else is just context and can be ignored if you know the answer to my question): How do I determine if an object is transient or not using JDO (or how do I write a short method that does this)?

Context for those who are curious or don't understance why I would want this:

I'm working w/JDO on GAE/J and am currently implementing the use of the app engine memcache api. I ran into a problem where I cache an instance of an entity from my datastore. At the end of the request my persistence manager is closed and - as far as I can tell the cached object becomes transient (I might be wrong about this) and hangs out in the cache.

Down the road, the cached object is used for building my view, etc, but when I go to do an update to the object and try and persist; the object doesn't persist (and rightfully so). I'm working around this by attempting to re-fetch the cached object before performing update operations. But this is introducing another problem because now when I am updating an object that doesn't happen to be cached it is managed by my persistence manager and any update operations I perform are overwritten when I fetch the fresh object. Basically, I'm doing this....

// valueWithChangesToUpdate is an object that could be from 
// memcache or could be fresh from pm, don't know for sure
// going into the method
public <T extends SomeKindOfEntity> void update(CustomQueryClass q, T valueWithChangesToUpdate) {

  // If valueWithChangesToUpdate is not from memcache/not transient then
  // any changes made are overridden when the following statement executes

  T freshObject = q.runQuery();


  // What I would like to do to avoid problem I'm having...
  // T freshObject = null;
  // if(valueWithChangesToUpdate.isTransient()) {
  //   freshObject = q.runQuery();
  // }

  // End goal...
  freshObject.applyUpdates(valueWithChangesToUpdate);
  PMF.getCurrentPM().makepersistent(freshObject);
}

If there is some other way I should be trying to do this or if I'm thinking about this wrong please feel free to point it out.


Solution

  • JDOHelper.getObjectState(obj);
    

    tells you definitively the state of the object. And

    JDOHelper.getPersistenceManager(obj);
    

    tells you the PM managing the object (if any). Documentation can be found in the JDO spec, or Apache JDO website.