Sam Goldberg - 2009-02-26

I have been incorporating EHCache into a legacy app which does NOT use Hibernate to persist objects to the database.  The objects have a "save" method which will either build an INSERT SQL or UPDATE SQL, depending on whether object has already been saved to the database.  The way this was implemented was to have a boolean flag on the object to indicate whether it is already in the database.  (You can see where this is going...)

Anyway, our cache implementation is using EHCache like a queue, and posting all the database update requests into the queue.  However, if there are multiple updates to the same object, and the object has already been flushed to disk by EHCache, then the state of the object is no longer shared with the object state in memory. 

So in this case, first cached object instance is updated to database and updates the "inDB" flag.  Next cache entry for that same object doesn't have that flag updated and tries to insert again, causing a failure.

I can think of some not so pretty ways to fix this problem, but was wondering if someone knows of an elegant solution.