Before I used hibernate, I had the luxery of working in a Process scoped identity environment. Meaning that when I fetch 2 times the same object from database they always == .
Before I moved to hibernate, I used to accomplish this by keeping a
HashMap of unique instances. Everytime I fetched a resultset I checked the previous instances inside this map in order to return the same object instance.
To avoid memory leaks and to help the garbage collector, I would first wrap these unique instances in
WeakReference objects before putting them in the map.
I moved (from this 10 year old framework) to hibernate to make sure that I stay up to date with recent java technologies. And I wrongly assumed that hibernate would support this out-of-the-box by now. Of course I get tempted to implement my own caching again. But my goal is really to setup the core of my project with the minimum of self-written code.
Actually most websites try to convince me not to use process scope identity at all, because it is supposed to be a dangerous thing (deadlocks, ...). In all honesty I am a bit sceptical, I am pretty sure I can manage.
I am currently considering to let process-scoped-identity behind me, but it looks like there are a lot of consequences. For example: in the past I sometimes stored information (calculated at runtime) in transient fields. Of course this is no longer possible now.
Some website wrote that it is possible to reach Process scoped identity with the EHCache framework. I tried but didn't succeed yet. By default it is clearly turned off, and I did not find any examples on how to activate it.
Some advice is more than welcome.
Process Scoped Identitywhen using Hibernate ?
Actually, what you implemented is supported out of the box is supported by Hibernate, in a given Hibernate session.
Having a unique instance shared between several sessions (and thus transactions) doesn't make any sense because that would ruin the ACID features provided by transactions, and make it completely useless unless only one user accesses the database. For example, your transient fields, stored in memory, would be completely incorrect is the data is modified in the database without going through this unique in-memory instance. And if some constraint is broken and causes a rollback of the transaction, you're left with incorrect values inside your unique instance, which are completely disconnected from the reality of the data stored in the database.