Context/Set-Up
We are using open-session-in-conversation-filter pattern in our application w/ Spring & Hibernate integration.
We are using Springs declarative transaction mgmt using the org.springframework.transaction.interceptor.TransactionProxyFactoryBean.
When the application gets a request we do multiple database activities (insert/updates) where update & inserts are individually flushed to database and transaction is committed.
Problem
Let's say for one of the insert/update there is a database exception thrown the hibernate session is closed as expected since the session is in an invalid state.
Even after this if I do not want to return the request back and want to continue with my request and complete the other activities I cant because the session is closed and any successive calls through this session fail and it's obvious why.
I need help in writing a solution where I can close the existing session and open a new one and attach the latest session to the thread using TransactionSynchronizationManager but not sure how to do that since there are many places where I might need to do this in the flow, is there a generic way to do this ? And is it even correct design?
And even if I achieve this what about the entities which are detached from the previous session how can I automatically attach to the new session so that proxies will work seamlessly?
The COnversation pattern just like the Extended Persistence Context in Java EE works just like you described here. If you get an Exception, you will have to discard everything and start from scratch.
Now, if you want more flexibility, you can just use detached entities and use a new
Sessionin every request which will merge the detached entities.However, what if an entity state will always cause the exception? How can you determine the entity and simply ignore it? What if it's linked to other entities.
Therefore, there is no simple solution to this issue. What you can do is:
HttpSession, Redis, etc.This way, the users will not lose the changes they did and based on the error message they can retry after applying corrections.