I want to perform a number of transactions in a row. All of which share common objects. I reuse one session for all of them to avoid loading an object in one session and updating it in another one. This is the code :
Code:
...
Transaction transaction = session.beginTransaction()
try {
...
session.saveOrUpdate(object);
...
transaction.commit();
} catch (Exception e)
{
transaction.rollback();
}
....
This piece of code is executed a couple times for different objects and transactions but the same session. The problem I am having is that after a rollback the session is neither cleared nor flushed and thus the session's first-level cache still contains updates and insert statements. These will be executed when the session is flushed next. I tried to fix this by flushing the session before the rollback. Someone suggested to clear the session instead. But I am not sure if that is a good idea because it seems like the same as creating a new session for every transaction.
What is the appropriate pattern in this scenario?