Lets recall transaction processing (Java with Spring) – part 2

So lets get back to the overview of transactions in Java with Spring Framework.

Bean-managed transactions can be:

  • container-managed transactions or declarative transaction management
  • application-managed transactions or programmatic transaction management

Declarative transaction management can be XML-based or annotation-based. A disadvantage of declarative transactions is: when a method is executing, it can be associated either with a single transaction or no transaction at all.

Programmatic transaction management gives more liberty. Take as example this pseudocode from Java EE 6 Tutorial (quite old but makes the point):

begin transaction
    update table-a
    if (condition-x)
   commit transaction
    else if (condition-y)
   update table-b
   commit transaction
   rollback transaction
   begin transaction
   update table-c
   commit transaction

This fine-grained programmatic dependency of when to commit or rollback can only be achieved without declarative transactions.

Transaction Propagation

Not mentioned so obvious is the fact of what is the DEFAULT propagation in Spring transactions.

  • The default propagation is REQUIRED
Propagation types and their behaviour
PROPAGATION TYPE no current transaction there’s a current transaction
MANDATORY throw exception use current transaction
NEVER don’t create a transaction, run method outside any transaction throw exception
NOT_SUPPORTED don’t create a transaction, run method outside any transaction suspend current transaction, run method outside any transaction
SUPPORTS don’t create a transaction, run method outside any transaction use current transaction
REQUIRED(default) create a new transaction use current transaction
REQUIRES_NEW create a new transaction suspend current transaction, create a new independent transaction
NESTED create a new transaction create a new nested transaction

Table is from ninjalj’s blog.

So lets see what this means in the context of a database connection and what the other propagation types.

And because I never went in too much detail here, I recommend to read Marco Behler’s blog to get the full picture.