To answer the first question: yes, it is possible to have several transactions in one session.
Is that a good idea? It depends.
The problem is that the data change in the first transaction will be performed, while it is not sure that the whole unit of work (session) will be fixed at the end. When you get, say, a StaleObjectException in a later transaction, you already have certain data. Note that this type of exception makes your session unusable, and you still had to destroy it. Then it’s hard to start all over and try again.
I would say it works well in these conditions:
- This is a user interface application.
- The changes only turned red in the last transaction.
User interface application
Errors are handled by the user interactively. This means that the user can see what is actually stored in case of an error and repeats the changes made.
Changes are only painted in the last transaction
A NH session only discards changes at the end, or "if necessary." In this way, you can save the changes to memory until the session is committed. The problem is that NH needs to clear the session before every request that is difficult to control. It can be turned off, which leads to side effects. When writing simple transactions, you can manage it. In a complex system, it is almost impossible to verify that nothing is happening.
Easy way (tm)
I wrote the persistence level of a rather large client-server system. In such a system, you do not have user processing errors directly. You need to handle errors in the system and return control to the client in a consistent state.
I have simplified all transaction processing to an absolute minimum to make it stable and “idiotic proof”. I always have a session and a transaction created together, and it becomes either perfect or not.
source share