This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
I have a collection of objects in memory, with their transient state and all. I originally load them via hibernate. I do reload them every once in a while to make sure my collection of objects is in sync with the database.
What I want to do is make sure that if an object has already been loaded, my objects (with their transient state) don't change under my feet. If an object has been added to the database, I want it added to my collection; if it has been modified in the database, I want MY object modified, not a new object created. Can I do that, or do I have to program all of it by hand? That would kind of defeat the purpose of an ORM, no?
You really shouldn't be holding on to sessions that long, so the probability of a concurrent change in the same data should be minimal. At that point, you can take an optimistic approach and use Hibernate's versioning mechanism. You keep a version number on the object. If its updated from the time you get the object until you commit it, then you'll get a stale object exception that you can handle by allowing the user to retry the operation, allowing them to merge the data (somehow), or by figuring out some automatic way of reconciling the issue.
I am developing a Swing application. It has Person objects. All transactions (and sessions) are very short-lived; Persons exist throughout the lifespan of the application and (obviously) beyond.
A Person has transitive state.
There is also an independent mechanism to CRUD a Person.
A normal Java object structure with property event model would have sufficed; but now (new to Hibernate as I am) I am wondering how to tie Hibernate into all that. I was hoping Hibernate would manage my object structure across sessions for me, building my object graph; turns out, it builds a graph of objects "like" my object (i.e. equals()), but since equals() is not good enough, I need ==, what's my solution, not rely on Hibernate's object graph at all? Do my own associations between objects programmatically?
Joined: May 14, 2008
Not to sound sarcastic, but if you want your transient state to be persisted, doesn't that make it not transient (i.e. persistent). If you want the state to persist and you want Hibernate to load it, you'll have to map it to the DB.
Joined: Mar 28, 2009
Javid, you are absolutely right, if I wanted my transient state to be persistent, I would have made it persistent. I don't, hence my question.
Are you familiar with Swing? Event listeners are one example of transient state. Or should I persist them?