The Programmer's Guide
  • About
  • Algorithm
    • Big O Notation
      • Tree
      • Problems
    • Basic Notes
    • Data Structure Implementation
      • Custom LinkedList
      • Custom Stack
      • Custom Queue
      • Custom Tree
        • Binary Tree Implementation
        • Binary Search Tree Implementation
        • Min Heap Implementation
        • Max Heap Implementation
        • Trie Implementation
      • Custom Graph
        • Adjacency List
        • Adjacency Matrix
        • Edge List
        • Bidirectional Search
    • Mathematical Algorithms
      • Problems - Set 1
      • Problems - Set 2
    • Bit Manipulation
      • Representation
      • Truth Tables
      • Number System
        • Java Program
      • Problems - Set 1
    • Searching
    • Sorting
    • Array Algorithms
    • String Algorithms
    • Tree
      • Tree Traversal Techniques
      • Tree Implementation
      • Applications of Trees
      • Problems - Set 1
    • Graph
      • Graph Traversal Techniques
      • Shortest Path Algorithms
      • Minimum Spanning Tree (MST) Algorithms
    • Dynamic Programming
      • Problems - Set 1
    • Recursion
    • Parallel Programming
    • Miscellaneous
      • Problems - Set 1
  • API
    • API Basics
      • What is an API?
      • Types of API
        • Comparison - TBU
      • Synchronous vs Asynchronous API
    • API Architecture
      • Synchronous & Asynchronous Communication
    • API Specification
  • Cloud Computing
    • Cloud Fundamentals
      • Cloud Terminology
      • Core Terminology
      • Cloud Models
      • Cloud Service Models
      • Benefits, Challenges and Risk of Cloud Computing
      • Cloud Ecosystem
  • Database
    • DBMS
      • Types of DBMS
        • Relational DBMS (RDBMS)
        • NoSQL DBMS
        • Object-Oriented DBMS (OODBMS)
        • Columnar DBMS
        • In-Memory DBMS
        • Distributed DBMS
        • Cloud-Based DBMS
        • Hierarchical DBMS
      • DBMS Architecture
      • DBMS Structure
    • SQL Databases
      • Terminology
      • RDBMS Concepts
        • Entity Relationship Diagram (ERD)
          • ERD Examples
        • Normalization
        • Denormalization
        • ACID & BASE Properties
          • ACID Properties
          • BASE Properties
        • Locking and Unlocking
      • SQL Fundamentals
        • SQL Commands
          • DDL (Data Definition Language)
          • DML (Data Manipulation Language)
          • DCL (Data Control Language)
          • TCL (Transaction Control Language)
          • DQL (Data Query Language)
        • SQL Operators
          • INTERSECT
          • EXCEPT
          • MINUS
          • IN and NOT IN
          • EXISTS and NOT EXISTS
        • SQL Clauses
          • Joins
          • OVER
          • WITH
          • CONNECT BY
          • MODEL
          • FETCH FIRST
          • KEEP
          • OFFSET with FETCH
        • SQL Functions
          • Oracle Specific
        • Others
          • Views
          • Indexing - TBU
          • Transactions - TBU
          • Triggers - TBU
      • Vendor-Specific Concepts
        • Oracle Specific
          • Rownum vs Rowid
          • Order of Execution of the query
          • Keys
          • Tablespace
          • Partition
      • Best Practice
      • Resources & References
        • O’Reilly SQL Cookbook (2nd Edition)
          • 1. Retrieving Records
          • 2. Sorting Query Results
          • 3. Working with Multiple Tables
          • 4. Inserting, Updating, and Deleting
          • 5. Metadata Queries
          • 6. Working with Strings
          • 7. Working with Numbers
          • 8. Date Arithmetic
          • 9. Date Manipulation
          • 10. Working with Ranges
          • 11. Advanced Searching
          • 12. Reporting and Reshaping
          • 13. Hierarchical Queries
          • 14. Odds 'n' Ends
    • SQL vs NoSQL
    • Best Practices
  • Git
    • Commands
      • Setup and Configuration Commands
      • Getting and Creating Projects
      • Tracking Changes
      • Branching and Merging
      • Sharing and Updating Projects
      • Inspection and Comparison
      • Debugging
      • Patching
      • Stashing and Cleaning
      • Advanced Manipulations
      • Other Commands
    • Workflows
  • Java
    • Java Installation
    • Java Distributions
    • Java Platform Editions
      • Java SE
      • Java EE
      • Jakarta EE
      • Java ME
      • JavaFX
    • Java Overview
      • OOP Principles
        • Encapsulation
        • Inheritance
        • Polymorphism
        • Abstraction
          • Abstract Class & Method
          • Interface
            • Functional Interfaces
            • Marker Interfaces
          • Abstract Class vs Interface
      • OOP Basics
        • What is a Class?
          • Types of Classes
        • What is an Object?
          • Equals and HashCode
            • FAQ
          • Shallow Copy and Deep Copy
          • Ways to Create Object
          • Serialization & Deserialization
        • Methods & Fields
          • Method Overriding & Overloading
          • Method Signature & Header
          • Variables
        • Constructors
        • Access Modifiers
      • Parallelism and Concurrency
        • Ways to Identify Thread Concurrency or Parallelism
        • Thread Basics
          • Thread vs Process
          • Creating Threads
          • Thread Context Switching
          • Thread Lifecycle & States
          • Runnable & Callable
          • Types of Threads
          • Thread Priority
        • Thread Management & Synchronisation
          • Thread Resource Sharing
          • Thread Synchronization
            • Why is Synchronization Needed?
            • Synchronized Blocks & Methods
          • Thread Lock
            • Types of Locks
            • Intrinsic Lock (Monitor Lock)
            • Reentrant Lock
          • Semaphore
          • Thread Starvation
          • Thread Contention
          • Thread Deadlock
          • Best Practices for Avoiding Thread Issues
      • Keywords
        • this
        • super
        • Access Modifiers
      • Data Types
        • Default Values
        • Primitive Types
          • byte
          • short
          • int
          • long
          • float
          • double
          • char
          • boolean
        • Non-Primitive (Reference) Types
          • String
            • StringBuilder
            • StringBuffer
              • Problems
            • Multiline String
            • Comparison - String, StringBuilder & StringBuffer
          • Array
          • Collections
            • List
              • Array vs List
              • ArrayList
              • Vector
                • Stack
                  • Problems
              • LinkedList
            • Queue
              • PriorityQueue
              • Deque (Double-Ended Queue)
                • ArrayDeque
                • ConcurrentLinkedDeque - TBU
                • LinkedBlockingDeque - TBU
            • Map
              • HashMap
              • Hashtable
              • LinkedHashMap
              • ConcurrentHashMap
              • TreeMap
              • EnumMap
              • WeakHashMap
            • Set
              • HashSet
              • LinkedHashSet
              • TreeSet
              • EnumSet
              • ConcurrentSkipListSet
              • CopyOnWriteArraySet
        • Specialized Classes
          • BigInteger
          • BigDecimal
            • Examples
          • BitSet
          • Date and Time
            • Examples
          • Optional
          • Math
          • UUID
          • Scanner
          • Formatter
            • Examples
          • Properties
          • Regex (Pattern and Matcher)
            • Examples
          • Atomic Classes
          • Random
          • Format
            • NumberFormat
            • DateFormat
            • DecimalFormat
        • Others
          • Object
          • Enum
            • Pre-Defined Enum
            • Custom Enum
            • EnumSet and EnumMap
          • Record
          • Optional
          • System
          • Runtime
          • ProcessBuilder
          • Thread and ThreadGroup - TBU
          • Class
          • Void
          • Throwable
            • Error
            • Exception
              • Custom Exception Handling
              • Best Practice
            • Error vs Exception
            • StackTraceElement
          • Logger - TBU
          • ResourceBundle - TBU
    • Java Features by Version
      • How New Java Features are Released ?
      • Java Versions
        • Java 8
        • Java 9
        • Scoped Values
        • Unnamed Variables & Patterns
      • FAQ
    • Concepts
      • Set 1
        • Streams
          • flatmap
          • Collectors Utility Class
          • Problems
        • Functional Interfaces
          • Standard Built-In Interfaces
          • Custom Interfaces
        • Annotation
          • Custom Annotation
          • Meta Annotation
        • Generics
          • Covariance and Invariance
        • Asynchronous Computation
          • Future
          • CompletableFuture
          • Future v/s CompletableFuture
          • ExecutorService
            • Thread Pool
            • Types of Work Queues
            • Rejection Policies
            • ExecutorService Implementations
            • ExecutorService Usage
          • Locks, Atomic Variables, CountDownLatch, CyclicBarrier - TBU
          • Parallel Streams, Fork/Join Framework,Stream API with Parallelism - TBU
      • Set 2
        • Standards
          • ISO Standards
          • JSR
            • JSR 303, 349, 380 (Bean Validation)
        • Operator Precedence
      • Set 3
        • Date Time Formatter
        • Validation
      • Set 4
        • Input from User
        • Comparison & Ordering
          • Object Equality Check
          • Comparable and Comparator
            • Comparator Interface
          • Sorting of Objects
          • Insertion Ordering
    • Packages
      • Core Packages
        • java.lang
          • java.lang.System
          • java.lang.Thread
      • Jakarta Packages
        • jakarta.validation
        • javax.validation
      • Third-party Packages
    • Code Troubleshoot
      • Thread Dump
      • Heap Dump
    • Code Quality & Analysis
      • ArchUnit
      • Terminologies
        • Cyclic dependencies
    • Code Style
      • Naming Convention
    • Tools
      • IntelliJ IDEA
        • Shortcuts for MAC
      • Apache JMeter
        • Examples
      • Thread Dump Capture
        • jstack
        • VisualVM - TBU
        • jcmd - TBU
        • JConsole - TBU
        • YourKit Java Profiler - TBU
        • Eclipse MAT - TBU
        • IntelliJ IDEA Profiler - TBU
        • AppDynamics - TBU
        • Dynatrace - TBU
        • Thread Dump Analyzers - TBU
      • Heap Dump Capture
        • jmap
        • VisualVM - TBU
        • jcmd - TBU
        • Eclipse MAT (Memory Analyzer Tool) - TBU
        • IntelliJ IDEA Profiler - TBU
        • YourKit Java Profiler - TBU
        • AppDynamics - TBU
        • Dynatrace - TBU
        • Kill -3 Command - TBU
        • jhat (Java Heap Analysis Tool) - TBU
        • JVM Options - TBU
      • Wireshark
        • Search Filters
    • Best Practices
      • Artifact and BOM Versioning
  • Maven
    • Installation
    • Local Repository & Configuration
    • Command-line Options
    • Build & Lifecycle
    • Dependency Management
      • Dependency
        • Transitive Dependency
        • Optional Dependency
      • Dependency Scope
        • Maven Lifecycle and Dependency Scope
      • Dependency Exclusions & Overrides
      • Bill of Materials (BOM)
      • Dependency Conflict Resolution
      • Dependency Tree & Analysis
      • Dependency Versioning Strategies
    • Plugins
      • Build Lifecycle Management
      • Dependency Management
      • Code Quality and Analysis
      • Documentation Generation
      • Code Generation
      • Packaging and Deployment
      • Reporting
      • Integration and Testing
      • Customization and Enhancement
        • build-helper-maven-plugin
        • properties-maven-plugin
        • ant-run plugin
        • exec-maven-plugin
        • gmavenplus-plugin
      • Performance Optimization
    • FAQs
      • Fixing Maven SSL Issues: Unable to Find Valid Certification Path
  • Spring
    • Spring Basics
      • What is Spring?
      • Why Use Spring
      • Spring Ecosystem
      • Versioning
      • Setting Up a Spring Project
    • Core Concepts
      • Spring Core
        • Dependency Injection (DI)
        • Stereotype Annotation
      • Spring Beans
        • Bean Lifecycle
        • Bean Scope
          • Singleton Bean
        • Lazy & Eager Initialization
          • Use Case of Lazy Initialization
        • BeanFactory
        • ApplicationContext
      • Spring Annotations
        • Spring Boot Specific
        • Controller Layer (Web & REST Controllers)
        • Service Layer (Business Logic)
        • Repository Layer (Data Access)
        • Dependency Injection & Configuration
        • Validation & Binding
        • Caching
        • AOP (Aspect-Oriented Programming)
        • Scheduling
        • Testing - TBU
        • Security
    • Spring Features
      • Auto Configuration
        • Spring Boot 2: spring.factories
        • Spring Boot 3: spring.factories
      • Spring Caching
        • In-Memory Caching
      • Spring AOP
        • Before Advice
        • After Returning Advice
        • After Throwing Advice
        • After (finally) Advice
        • Around Advice
      • Spring File Handling
        • Apache Camel - TBU
          • Local Docker Setup for SFTP Server
      • Reactive Programming
        • Reactive System
        • Reactive Stream Specification
        • Project Reactor
          • Mono & Flux
      • Asynchronous Computation
        • @Async annotation
        • Context Propagation - TBU
      • Spring Security
        • Authentication
          • Core Components
            • Security Filter Chain
              • HttpSecurity
              • Example
            • AuthenticationManager
            • AuthenticationProvider
            • UserDetailsService
              • UserDetails
              • PasswordEncoder
            • SecurityContext
            • SecurityContextHolder
            • GrantedAuthority
            • Security Configuration (Spring Security DSL)
          • Authentication Models
            • One-Way Authentication
            • Mutual Authentication
          • Authentication Mechanism
            • Basic Authentication
            • Form-Based Authentication
            • Token-Based Authentication (JWT)
            • OAuth2 Authentication
            • Multi-Factor Authentication (MFA)
            • SAML Authentication
            • X.509 Certificate Authentication
            • API Key Authentication
            • Remember-Me Authentication
            • Custom Authentication
          • Logout Handling
        • Authorization
        • Security Filters and Interceptors
        • CSRF
          • Real-World CSRF Attacks & Prevention
        • CORS
        • Session Management and Security
        • Best Practices
      • Spring Persistence
        • JDBC
          • JDBC Components
          • JDBC Template
          • Transaction Management
          • Best Practices in JDBC Usage
          • Datasource
            • Connection Pooling
              • HikariCP
            • Caching
        • JPA (Java Persistence API)
          • JPA Fundamentals
          • ORM Mapping Annotations
            • 1. Entity and Table Mappings
            • 2. Field/Column Mappings
            • 3. Relationship Mappings
            • 4. Inheritance Mappings
            • 5. Additional Configuration Annotations
          • Querying Data
            • JPQL
            • Criteria API
            • JPA Specification
              • Example - Employee Portal
            • Native SQL Queries
            • Named Queries
            • Query Return Types
            • Pagination & Sorting
              • Example - Employee Portal
            • Projection
          • Fetch Strategies in JPA
        • JPA Implementation
          • Hibernate
            • Properties
            • Example
        • Spring Data JPA
          • Repository Abstractions
          • Entity-to-Table Mapping
          • Derived Query Methods
        • Cross-Cutting Concerns
          • Transactions
          • Caching
          • Concurrency
        • Examples
          • Employee Portal
            • API
    • Distributed Systems & Communication
      • Distributed Scheduling
      • Distributed Tracing
      • Inter-Service Communication
        • 1. RestTemplate
        • 2. WebClient
        • 3. OpenFeign
        • Retry Mechanism
          • @Retryable annotation
            • Example
    • Security & Data Protection
      • Encoding | Decoding
        • Types
          • Base Encoding
            • Base16 - TBD
              • Encoding and Decoding in Java - TBD
            • Base32
              • Encoding and Decoding in Java
            • Base64 -TBD
              • Encoding and Decoding in Java - TBD
          • Text Encoding - TBD
            • Extended ASCII
              • Encoding and Decoding in Java - TBD
                • ISO-8859-1
                • Windows-1252 - TBD
                • IBM Code Pages - TBD
            • ASCII
              • Encoding and Decoding in Java
        • Java Guidelines
          • Text Encoding Decoding Examples
          • Base Encoding Decoding Examples
          • Best Practices and Concepts
          • Libraries
      • Cryptography
        • Terminology
        • Java Cryptography Architecture (JCA)
        • Key Management
          • Key Generation
            • Tools and Libraries
              • OpenSSL
              • Java Keytool
                • Concept
                • Use Cases
            • Key & Certificate File Formats
          • Key Distribution
          • Key Storage
          • Key Rotation
          • Key Revocation
        • Encryption & Decryption
          • Symmetric Encryption
            • Algorithm
            • Modes of Operation
            • Examples
          • Asymmetric Encryption
            • Algorithm
            • Mode of Operation
            • Examples
    • Utilities & Libraries
      • Apache Libraries
        • Apache Camel
          • Camel Architecture
            • Camel Context
            • Camel Endpoints
            • Camel Components
            • Camel Exchange & MEP
          • Spring Dependency
          • Different Components
            • Camel SFTP
        • Apache Commons Lang
      • MapStruct Mapper
      • Utilities by Spring framework
        • FileCopyUtils
    • General Concepts
      • Spring Boot Artifact Packaging
      • Classpath and Resource Loading
      • Configuration - Mapping Properties to Java Class
      • Validations in Spring Framework
        • Jakarta Validation
          • Jakarta Bean Validation Annotations
    • Practical Guidelines
      • Spring Configuration
      • Spring Code Design
  • Software Testing
    • Software Testing Methodologies
      • Functional Testing
      • Non Functional Testing
    • Software Testing Life Cycle (STLC)
    • Integration Test
      • Dynamic Property Registration
    • Java Test Framework
      • JUnit
        • JUnit 4
          • Examples
        • JUnit 5
          • Examples
        • JUnit 4 vs JUnit 5
  • System Design
    • Low-Level Design (LLD)
      • Programming Paradigms
      • Design Pattern
        • Creational Pattern
        • Structural Pattern
        • Behavioral Pattern
        • Examples
          • Data Collector
          • Payment Processor
      • Object-Oriented Design
        • SOLID Principles
        • GRASP Principles
        • Composition
        • Aggregation
        • Association
      • Design Enhancements
        • Fluent API Design
          • Examples
    • High-Level Design (HLD)
      • CAP Theorem
      • Load Balancer
        • Load Balancer Architecture
        • Load Balancing in Java Microservices
          • Client-Side Load Balancing Example
          • Server-Side Load Balancing Example
        • Load Balancer Monitoring Tool
      • Architecture
        • Event Driven Architecture
          • Event-Driven Microservices
          • Handling Failures & Retry Mechanisms
          • Event Schema Design (Avro, JSON, Protobuf)
          • Persistence & Non-Persistence Queues
          • Technologies & Frameworks
            • ActiveMQ - TBU
            • Kafka - TBU
      • Scaling
        • Vertical Scaling (Scaling Up)
        • Horizontal Scaling (Scaling Out)
        • Auto-Scaling
        • Database Scaling via Sharding
      • Networking Metrics
        • Types of Delay
        • Scenario
      • System Characteristics
      • Workload Types
      • Resilience & Failure Handling
    • Security
      • Security by Design
      • Zero Trust Security Model
      • Zero Trust Architecture
      • Principles
        • CIA
        • Least Privilege Principle
        • Defense in Depth
      • Security Threats & Mitigations
        • OWASP
          • Top 10 Security Threats
          • Application Security Verification Standard
          • Software Assurance Maturity Model
          • Dependency Check
          • CSRFGuard
          • Cheat Sheets
          • Security Testing Guide
          • Threat Dragon
        • Threat Modeling
      • Compliance & Regulation
        • PCI DSS
    • Deployment Patterns
    • Diagrams
      • UML Diagrams
        • PlantUML
          • Class Diagram
          • Object Diagram
          • Sequence Diagram
          • Use Case Diagram
          • Activity Diagram
          • State Diagram
          • Architecture Diagram
          • Component Diagram
          • Timing Diagram
          • ER Diagram (Entity-Relationship)
          • Network Diagram
    • Common Terminologies
    • Problems
      • Reference Materials
      • Cache Design
  • Interview Guide
    • Non-Technical
      • Behavioural or Introductory Guide
      • Project Specific
    • Technical
      • Java Interview Companion
        • Java Key Concepts
          • Set 1
          • Set 2
        • Java Code Snippets
        • Java Practice Programs
          • Set 1 - Maths theory & Pattern
          • Set 2 - Arrays
          • Set 3 - Strings
          • Set 4 - Search
          • Set 5 - Streams and Collection
      • SQL Interview Companion
        • SQL Practice Problems
          • Set 1
      • Spring Interview Companion
        • Spring Key Concepts
          • Set 1 - General
          • Set 2 - Core Spring
        • Spring Code Snippets
      • Application Server
      • Maven
      • Containerized Application
      • Microservices
    • General
      • Applicant Tracking System (ATS)
      • General Interview Preparation Tips - TBU
      • Flowchart - How to Solve Coding Problem?
  • Personal Projects
    • Hackathon
Powered by GitBook
On this page
  • About
  • Spring Transaction Management
  • Important Terminology
  • 1. Dirty Read
  • 2. Non-Repeatable Read
  • 3. Phantom Read
  • Transactional Attributes
  • 1. Propagation
  • 2. Isolation
  • 3. ReadOnly
  • 4. timeout
  • 5. RollbackFor and noRollbackFor
  • Combining Attributes
  • Does Propagation Matters only when there are several methods calls inside a method ?
  • Case 1: Single transactional method with repository call
  • Case 2: Method A calls Method B (both annotated)

Was this helpful?

  1. Spring
  2. Spring Features
  3. Spring Persistence
  4. Cross-Cutting Concerns

Transactions

About

A transaction is a sequence of operations performed as a single logical unit of work. A transaction has four key properties, commonly known as ACID:

  • Atomicity: All operations in the transaction are completed; if one fails, all are rolled back.

  • Consistency: The database remains in a consistent state before and after the transaction.

  • Isolation: Transactions are isolated from each other.

  • Durability: Once a transaction is committed, its effects are permanent.

Spring Transaction Management

Spring provides declarative transaction management using the @Transactional annotation. We can also use programmatic transaction management using PlatformTransactionManager, but declarative is most common.

Basic Usage

@Transactional
public void transferFunds(Account from, Account to, double amount) {
    from.debit(amount);
    to.credit(amount);
    accountRepository.save(from);
    accountRepository.save(to);
}
  • If any exception is thrown, all operations are rolled back.

  • By default, only unchecked exceptions (RuntimeException, Error) trigger rollback.

  • To rollback on checked exceptions, specify it explicitly:

@Transactional(rollbackFor = Exception.class)

Important Terminology

1. Dirty Read

A dirty read happens when a transaction reads data that has been modified by another transaction but not yet committed.

Example:

  • Transaction A updates a row's value but hasn't committed yet.

  • Transaction B reads the updated value (which is uncommitted).

  • If Transaction A rolls back, Transaction B has read a value that never officially existed.

Prevented by: READ_COMMITTED, REPEATABLE_READ, SERIALIZABLE

2. Non-Repeatable Read

A non-repeatable read occurs when a transaction reads the same row twice and gets different values, because another transaction modified and committed changes in between the two reads.

Example:

  • Transaction A reads a row.

  • Transaction B updates and commits that same row.

  • Transaction A reads the row again and sees a different value.

Prevented by: REPEATABLE_READ, SERIALIZABLE

3. Phantom Read

A phantom read occurs when a transaction runs the same query twice and gets additional rows the second time, due to another transaction inserting new data that matches the query criteria.

Example:

  • Transaction A queries all employees with salary > 50k.

  • Transaction B inserts a new employee with salary 60k and commits.

  • Transaction A runs the query again and sees a new row it didn’t see before.

Prevented by: SERIALIZABLE (the strictest isolation level)

Transactional Attributes

When we annotate a method or class with @Transactional, Spring manages the transaction boundaries for us. The annotation supports several key attributes that modify transactional behavior.

Attribute
Description

propagation

Defines how transactions relate to each other.

isolation

Defines the isolation level for the transaction.

readOnly

Marks transaction as read-only for performance optimization.

timeout

Specifies the time in seconds before a transaction times out.

rollbackFor

Specifies which exceptions trigger a rollback.

1. Propagation

The propagation attribute in Spring's @Transactional annotation defines how a transactional method should behave when it is called from another transactional context. It determines whether the method should join an existing transaction, start a new one, or execute without any transaction. The default value, REQUIRED, means that the method will participate in the current transaction if one exists or start a new one if not.

Why Propagation Matters?

In a multi-layered application, service methods often call other service methods. These methods may or may not be transactional. Propagation determines:

  • Whether a new transaction should be created.

  • Whether the existing transaction should be used.

  • Whether the current transaction should be suspended.

  • Whether a transaction is even allowed.

Common Values:

Propagation Type
Description

REQUIRED (default)

Joins existing transaction or starts a new one if none exists.

REQUIRES_NEW

Suspends the current transaction and starts a new one.

SUPPORTS

Runs in a transaction if one exists; otherwise, runs non-transactionally.

NOT_SUPPORTED

Always runs non-transactionally, suspending any current transaction.

NEVER

Must not run in a transaction; throws exception if a transaction exists.

MANDATORY

Must run within an existing transaction; throws exception if none exists.

NESTED

Executes within a nested transaction (uses savepoints); rollback only affects inner scope.

Example:

@Transactional(propagation = Propagation.REQUIRES_NEW)
public void logAuditEvent(AuditEvent event) {
    auditRepo.save(event);
}

1. Propagation.REQUIRED

If a transaction already exists, the method will join that transaction. If there is no existing transaction, a new one will be started.

Most create, update, and delete operations should use REQUIRED. It's safe and ensures all database operations are rolled back together if something goes wrong.

@Transactional(propagation = Propagation.REQUIRED)
public void saveEmployee(Employee emp) {
    employeeRepository.save(emp); // Uses existing transaction or starts a new one
}

Behavior:

  • Outer method starts a transaction

  • Inner method joins the same transaction

  • If inner method fails, outer also rolls back

2. Propagation.REQUIRES_NEW

Always starts a new transaction. If a transaction is already active, it will be suspended until the new one completes.

Logging, auditing, or sending notifications where the operation should be committed even if the main transaction fails.

@Transactional(propagation = Propagation.REQUIRES_NEW)
public void logAudit(String action) {
    auditRepository.save(new Audit(action));
}
@Transactional
public void createEmployee(Employee emp) {
    employeeRepository.save(emp);
    logAudit("Employee created"); // Even if this fails, the employee is still saved
}

Behavior:

  • Outer method has a transaction

  • Inner method suspends outer transaction and runs in a new one

  • Failure in outer does not affect committed inner transaction

3. Propagation.SUPPORTS

If a transaction exists, join it. If not, run the method non-transactionally.

Read-only methods or reports that can execute inside or outside a transaction.

@Transactional(propagation = Propagation.SUPPORTS)
public List<Employee> getAllEmployees() {
    return employeeRepository.findAll();
}

Behavior:

  • Adapts to the context

  • Flexible for shared methods (read logic)

4. Propagation.NOT_SUPPORTED

The method will never run inside a transaction. If a transaction exists, it will be suspended.

Reporting, batch export jobs, or read-only operations where you don’t want transactional overhead.

@Transactional(propagation = Propagation.NOT_SUPPORTED)
public void exportDataToCSV() {
    // Will not participate in a transaction
    performExport();
}

Behavior:

  • Any existing transaction is suspended

  • No rollback will occur on failure

  • Can improve performance for long reads

5. Propagation.NEVER

The method must not run inside a transaction. If a transaction exists, Spring throws an exception.

Calls to third-party services or external systems that cannot be wrapped in a transaction.

@Transactional(propagation = Propagation.NEVER)
public void callExternalService() {
    // Throws exception if there is an active transaction
    thirdPartyAPI.sendData();
}

Behavior:

  • Enforces strict non-transactional context

  • Guarantees no database locks or rollbacks happen

6. Propagation.MANDATORY

The method must be executed inside an existing transaction. If no transaction exists, an exception is thrown.

Utility methods that modify shared data and should always be part of a larger transaction.

@Transactional(propagation = Propagation.MANDATORY)
public void updateStatistics() {
    // Fails if not called inside another transaction
    statisticsRepository.updateCounts();
}

Behavior:

  • Only works if called from another method with a transaction

  • Prevents accidental non-transactional writes

7. Propagation.NESTED

Runs inside a nested transaction. If the outer transaction rolls back, the nested one rolls back too. If the nested one fails, it can rollback independently using savepoints.

Use when you want part of a transaction to be rollback-safe without affecting the whole transaction.

@Transactional(propagation = Propagation.NESTED)
public void adjustSalary() {
    // Can rollback independently using savepoints
    updateBonuses();
    updateDeductions();
}
@Transactional
public void updateEmployeeDetails() {
    saveDetails();
    try {
        adjustSalary(); // Nested call
    } catch (Exception ex) {
        // Only salary changes rollback, not the entire employee update
    }
}

Behavior:

  • Requires database support for nested transactions

  • Useful when rollback granularity is needed

2. Isolation

The isolation attribute controls the level of visibility that one transaction has into the operations of another. It governs concurrency-related issues such as dirty reads, non-repeatable reads, and phantom reads. The attribute corresponds directly to isolation levels supported by the underlying database (e.g., READ_COMMITTED, REPEATABLE_READ, SERIALIZABLE).

Common Isolation Levels:

Isolation Level
Description

DEFAULT

Uses the default isolation level of the underlying database.

READ_UNCOMMITTED

Allows dirty reads; no isolation.

READ_COMMITTED (common)

Prevents dirty reads, but allows non-repeatable reads.

REPEATABLE_READ

Prevents dirty and non-repeatable reads; phantom reads may occur.

SERIALIZABLE

Highest isolation level; ensures full isolation, but has the lowest performance.

Example:

@Transactional(isolation = Isolation.REPEATABLE_READ)
public Employee getEmployeeDetails(Long id) {
    return employeeRepo.findById(id).orElseThrow();
}

3. ReadOnly

The readOnly attribute indicates that the transaction is not intended to perform any data modifications. When set to true, it serves as a hint to the transaction manager and the underlying persistence provider (like Hibernate) to optimize performance—for example, by skipping dirty checks or using non-locking queries. Although it does not enforce immutability at the database level, using readOnly = true is a best practice for methods that only fetch data, as it can reduce overhead and improve response times.

Usage:

  • Use it for service methods that only read data.

  • Helps prevent accidental updates.

Example:

@Transactional(readOnly = true)
public List<Employee> getAllEmployees() {
    return employeeRepo.findAll();
}

4. timeout

The timeout attribute specifies the maximum duration, in seconds, that the transaction is allowed to run. If the method execution exceeds this time, the transaction is automatically rolled back. This is particularly useful in high-load or time-sensitive applications, where long-running operations could lead to resource exhaustion or data contention. The default value is -1, which means no timeout. Setting an appropriate timeout helps prevent stalled transactions from holding database locks indefinitely.

Example:

@Transactional(timeout = 5)
public void performLongTask() {
    // Will be rolled back if it takes longer than 5 seconds
}

5. RollbackFor and noRollbackFor

By default, Spring only rolls back transactions for unchecked exceptions (i.e., subclasses of RuntimeException and Error). The rollbackFor attribute allows customization of this behavior by explicitly declaring one or more exception types (including checked exceptions) that should trigger a rollback. This is useful when you want a transaction to roll back for business exceptions or application-specific errors that aren't runtime exceptions. It enhances control over transactional boundaries, especially in multi-layered applications.

By Default:

  • Unchecked exceptions (RuntimeException, Error) → cause rollback

  • Checked exceptions → do not cause rollback unless specified

Use rollbackFor to rollback for specific exceptions:

@Transactional(rollbackFor = IOException.class)
public void updateFile() throws IOException {
    // Will rollback even on checked IOException
}

Use noRollbackFor to ignore rollback for specific exceptions:

@Transactional(noRollbackFor = CustomWarningException.class)
public void updateData() throws CustomWarningException {
    // Will not rollback for CustomWarningException
}

Combining Attributes

We can use multiple attributes together for fine-grained control:

Example:

@Transactional(
    propagation = Propagation.REQUIRED,
    isolation = Isolation.READ_COMMITTED,
    timeout = 10,
    readOnly = false,
    rollbackFor = {SQLException.class}
)
public void processTransaction() {
    // your logic here
}

Does Propagation Matters only when there are several methods calls inside a method ?

Propagation only matters when transactional methods call other transactional methods. It does not matter if you're making a direct call to a repository method without involving another service-level transactional method.

Case 1: Single transactional method with repository call

@Transactional(propagation = Propagation.REQUIRED)
public void createEmployee(Employee emp) {
    employeeRepository.save(emp); // Transaction starts here, managed by Spring
}
  • There's no method call to another service.

  • Here, propagation does not come into play meaningfully — REQUIRED is the default and it will simply begin a new transaction.

Case 2: Method A calls Method B (both annotated)

@Service
public class EmployeeService {

    @Transactional(propagation = Propagation.REQUIRED)
    public void methodA() {
        // do something
        methodB(); // Propagation rules apply here!
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void methodB() {
        // do something
    }
}
  • This is where propagation matters.

  • Spring checks if a transaction is already running when methodA() calls methodB().

  • Based on the propagation type, it will decide whether to reuse, suspend, or throw an exception.

⚠️ Important Caveat – Internal method calls don’t trigger Spring’s proxy mechanism

public void methodA() {
    methodB(); // Even if methodB has @Transactional, it's not applied here
}
  • If methodA() and methodB() are in the same class, and one calls the other directly, Spring will not apply transaction propagation.

  • This is because Spring AOP uses proxies, and a direct internal method call bypasses the proxy.

Workaround: Split methodB into a separate bean/service, or inject the current service into itself using a proxy-aware pattern.

PreviousCross-Cutting ConcernsNextCaching

Last updated 8 days ago

Was this helpful?