Declarative or Programmatic Transaction in Spring

Programmatic Transaction Management

  1. Allows us to manage transactions through programming in our source code.
  2. This means hardcoding transaction logic between our business logic.
  3. We use programming to manage transactions
  4. Flexible, but difficult to maintain with large amount of business logic. Introduces boilerplate between business logic.
  5. Preferred when relative less transaction logic is to be introduced.

Declarative Transaction Management

  1. Allows us to manage transactions through configuration.
  2. This means separating transaction logic with business logic.
  3. We use annotations (Or XML files) to manage transactions.
  4. Easy to maintain. Boilerplate is kept away from business logic.
  5. Preferred when working with large amount of Transaction logic.

Spring offers both programmatic and declarative transactions.

Programmatic means you have transaction management code surrounding your business code. This gives extreme flexibility, but is difficult to maintain and, well, boilerplate.

Declarative means you separate transaction management from the business code. You can use annotations or XML based configuration.

programmatic management is more flexible during development time but less flexible during application life
declarative management is less flexible during development time but more flexible during application life

http://docs.spring.io/spring/docs/3.0.x/reference/transaction.html

Declarative Transaction Management allows to eliminate any dependencies on the transaction framework from the Java code. The four participants to provide the transaction support are transaction manager, proxy factory, transaction interceptor, and a set of transaction attributes.

Suggest to use Declarative Transaction Management, Alternative for HibernateTemplates either NamedJDBCTemplate or simpleJDBCTemplate


They are not mutually exclusive.

You can use decalrative transaction management (@Transactional) in most of cases, and fall back to programmatic transaction management (TransactionTemplate) when you face limitations of Spring AOP (see 11.5.1 Understanding the Spring Framework's declarative transaction implementation) or need to control transactions in more complex ways.

Tags:

Spring