I am developing a multi-threaded application and therefore I am currently trying to figure out a way to always fetch latest state of my entity instances from the database before making changes to any of their fields.
From the hibernate documentation I've read the following about the session.update()
method:
In other words, update() is usually the first method you would call in a fresh session, ensuring that the reattachment of your detached instances is the first operation that is executed.
On the other hand the java doc comment for session.refresh()
tells me that I can use this method to reload the current state for some entity.
I am kinda confused that in examples the refresh method is always used at the end of a unit of work rather than at the beginning. Why would I first call update before making changes?
I thought of a workflow like thid to update my entity instances:
public void modifySomeFields() {
// get the session that is currently used by this thread from the context
Transaction tx = session.beginTransaction();
try {
session.refresh(this);
// modify some fields
session.update(this);
tx.commit(); // flush session
} catch (HibernateException e) {
// handle exception
tx.rollback();
}
// reuse the session for further transactions in the same thread
}
Is this a valid approach or did I understand the refresh method wrong? Or is it just bad practice to handle updates like this?
EDIT:
As of what I have read is that a simple call to session.update()
just re-attaches the entity to the session. But what I don't understand is if I call update
on a entity instance that contains old state from the database then wouldn't I run into lost updates?
What I ask for is a way to re-attach an instance to a session that does not contain the latest state and I want to update it to the latest state (and not make the instances current state the latest state). Then I want to make changes to the entity instance and send them to the database such that if I re-attach the same db entity instance (but other java object) to another session I can fetch the latest db state and then make my modifications.
The reason is that I don't always want to fetch a new persistent instance if I do work with my entities because I have some transient state savd on them that I require throughout the whole lifetime of the clients that the entities correspond to.