I have been troubleshooting some blocking issues with my Hibernate+SQL Server + READ_COMMITTED configuration. I've come to a conclusion that its absolutely critical for application code to stick with the following processing flow to minimize blocking issues.
READ DATA PROCESS WRITE DATA COMMIT
Essentially, once the WRITE DATA stage begins, SQL server starts taking locks that can block other readers (in its default configuration). So the application should try to minimize the time between WRITE DATA & COMMIT.
Hibernate makes sticking to that reasonably easy with its session management and "deferred" updates. In my setup, the TX COMMIT occurs immediately after flush. If the application writes are deferred to flush time, I am in great shape.
One area I've struggled with is the insertion of new entities who have a database generated auto-number key. Hibernate immediately does the insert (presumably to get the key assigned). If that happens to occur early in the workflow, SQL server takes locks that are held for a lengthier & unpredictable amount of time until the workflow completes and COMMIT happens.
I have tried various methods: save(),persist(),setFlushMode() to get "deferred insert" but I haven't been successful. Its easy enough when the new entity is added to cascaded collection. The dirty checking happens at flush time so the insert does as well. Standalone entities are a problem though.
My current work around is to use Spring's TransactionSynchronization manager to defer the persist call until the "beforeCommit" call which occurs *just* before flush & commit time. It works but I'm wondering if I''m just missing something that would make this simpler.
Is there anything else I can do to force the deferral of an insert until flush time?
|