In my DAO I use a convention where a method starting with
load returns a persistent object and a method starting with
find returns a non-persistent object (i.e. a 'safe to alter'/'readonly' one).
Currently I am implementing the find style methods using
session.evict(object).
However, this has the following problem:
If I load a persistent object and alter it, but then subsequently find the same object (as part of a list returned by a general query, for example), my changes to the persistent object have been lost - my find has evicted it from the session cache and therefore made in non-persistent.
I am trying to find a better solution. I need to be able to supply both persistent and non-persistent copies of an object within the scope of a transaction, without them interfering with each other. I want to keep the solution as close to Hibernate as possible to avoid polluting business logic.
So far I see 3 options:
Make all classes in my model Cloneable, then get the find methods to supply clones. I guess this would work, but it means polluting my model, and all the objects I find will still end up in the session cache.
Try to keep a copy of the session cache, so I know which objects the find methods should evict. I have my doubts that the API exists to get my fingers deep enough into Hibernate b to do this. Also, this seems pretty ugly to me.
Run two sessions in parallel for each unit of work, one for getting persistent objects, the other for getting non-persistent objects. The readonly session would be FlushMode.NEVER, and then clear it's cache just before flushing and closing. However, I assume for these two sessions to play nicely, they would require two separate JDBC connections. I imagine my WebLogic 8.1 would supply these transparently, but I have just doubled the number of connections I require.
My questions are:
What are other people's experiences with this issue (a requirement to get both a persistent and a non-persistent copy of a object out of Hibernate in a single unit of work)?
Which solution do experienced Hibernators recommend? Or is there a better one out there?
Thanks very much ...