Spring @Transactional: All or Nothing, the Proxy, and the Self-Call Trap
Assigning a Relay ticket is two writes: update the ticket, add a comment. Watch it end half done without a transaction, roll back cleanly with @Transactional, and break again when the method is called from inside its own class.
What you will learn
- Make two database writes all or nothing with @Transactional
- Read the transaction TRACE log to see commit and rollback
- Explain why a call from inside the same class skips the transaction
- Use readOnly = true and know PostgreSQL's default isolation level
Before you start
- Spring Boot Repository and Service Layer
- JPA Entity Mapping: Ids, Enums and Dates
Ticket 7 in Relay is open. Olivia asks how to add a team member, and nobody is assigned yet. An agent takes it, and that means two database writes:
- Update the ticket: status
IN_PROGRESS, assignee Liam Foster. - Add a comment with a note.
These two belong together. Both happen, or neither does. If write 2 fails, write 1 must be undone. One annotation does that, and it hides one trap.
The service
@Service
public class TicketService {
private final TicketRepository tickets;
private final AgentRepository agents;
private final CommentRepository comments;
public TicketService(TicketRepository tickets, AgentRepository agents, CommentRepository comments) {
this.tickets = tickets;
this.agents = agents;
this.comments = comments;
}
// Two writes that belong together: all or nothing
@Transactional
public void assign(Long ticketId, Long agentId, String note) {
Ticket ticket = tickets.findById(ticketId).orElseThrow();
Agent agent = agents.findById(agentId).orElseThrow();
ticket.assignTo(agent);
ticket.changeStatus(Status.IN_PROGRESS);
tickets.save(ticket); // write 1
comments.save(new Comment(ticket, "Relay", note)); // write 2
}
@Transactional
public void assignAll(Long agentId, List<Long> ticketIds) {
for (Long ticketId : ticketIds) {
assign(ticketId, agentId, "Assigned in a batch");
}
}
// Reads only: tell Spring and the database that nothing is written here
@Transactional(readOnly = true)
public long countAssigned(Long agentId) {
return tickets.countByAssigneeId(agentId);
}
}
To see what Spring does, the project turns on TRACE logging for org.springframework.transaction.interceptor. That's where the "Getting transaction for" and "Completing transaction for" lines come from.
The comment fails, the ticket stays
A runner calls assign(7, 1, null). The note is null, and the comment's body column is not null, so write 2 must fail:
service is a TicketService$$SpringCGLIB$$0
TRACE Getting transaction for [TicketService.assign]
WARN ERROR: null value in column "body" of relation "comment" violates not-null constraint
TRACE Completing transaction for [TicketService.assign] after exception: DataIntegrityViolationException
assign(7, 1, null) -> DataIntegrityViolationException
Look at the first line. The object the runner holds isn't your TicketService. It's a TicketService$$SpringCGLIB$$0, a proxy that Spring generated. The proxy opened the transaction, the comment insert failed, and "completing after exception" means it rolled back. psql confirms it:
id | status | assignee_id
----+--------+-------------
7 | OPEN |
8 | OPEN |
ticket_id | body
-----------+------
(0 rows)
Ticket 7 is still open, with nobody assigned and no comment. The service either finished the whole job or left the database exactly as it found it.
Break it 1: no annotation, half done
Delete the @Transactional line above assign and run the same call. The same exception comes back, but the database tells a different story:
id | status | assignee_id
----+-------------+-------------
7 | IN_PROGRESS | 1
8 | OPEN |
ticket_id | body
-----------+------
(0 rows)
Write 1 was saved on its own, and write 2 failed. The ticket says it's assigned, and nothing explains why. That's the bug you just avoided.
Break it 2: the self-call
Put the annotation back on assign, and remove it from assignAll instead. assign still has its own @Transactional, so it should be fine. Right? Run assignAll(1, [8, 999]); ticket 999 doesn't exist:
TRACE Getting transaction for [SimpleJpaRepository.findById]
TRACE Getting transaction for [SimpleJpaRepository.findById]
TRACE Getting transaction for [SimpleJpaRepository.save]
TRACE Getting transaction for [SimpleJpaRepository.save]
TRACE Getting transaction for [SimpleJpaRepository.findById]
assignAll(1, [8, 999]) -> NoSuchElementException
There's no "Getting transaction for TicketService" line at all. Only the repositories got their own little transactions. In psql, ticket 8 is IN_PROGRESS with the comment "Assigned in a batch", and the batch failed on 999. Half done again.
Why? assignAll calls assign(...), which really means this.assign(...). That's a plain Java call on the real object. It never passes through the proxy, so the annotation on assign is never read.
The fix is to put @Transactional on the outer method, the one called from outside. That's how the project ships it:
TRACE Getting transaction for [TicketService.assignAll]
TRACE Completing transaction for [TicketService.assignAll] after exception: NoSuchElementException
assignAll(1, [8, 999]) -> NoSuchElementException
Ticket 8 is still OPEN, there's no comment, and the whole batch rolled back.
Read-only and isolation
For a method that only reads, like countAssigned, write @Transactional(readOnly = true). It tells Spring and the database that nothing is written here.
Isolation decides what one transaction may see of another one running at the same time:
- Read committed: you see what others have committed. PostgreSQL's default.
- Repeatable read: the data stays as it was when your transaction began.
- Serializable: runs as if transactions went one at a time.
relay=# show default_transaction_isolation;
default_transaction_isolation
-------------------------------
read committed
The app's startup log agrees: Isolation level: READ_COMMITTED [default READ_COMMITTED]. For Relay, the default is fine.
Common mistakes
- Calling a
@Transactionalmethod from the same class. The proxy is skipped. Annotate the method that's called from outside. - Catching the exception inside the method. If the exception never reaches the proxy, the proxy commits.
- Putting
@Transactionalon the repository calls only. Each save then commits on its own, which is exactly the half-done case. - Creating the service with
new. No proxy, no transaction. Let Spring inject it.
Recap
| Run | Ticket after | Comment after |
|---|---|---|
assign with @Transactional | OPEN | none (rolled back) |
assign without it | IN_PROGRESS | none (half done) |
assignAll without it (self-call) | 8 IN_PROGRESS | 1 row (half done) |
assignAll with it | 8 OPEN | none (rolled back) |
Try it yourself
Call assign(7, 1, "Taking this one") with a real note. Which TRACE line do you expect now instead of "after exception", and what do the two psql queries show?
Related course on Udemy
FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE
Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)Related posts
Spring Boot Repository and Service Layer: Save and Read Data Without Writing SQL
A one-line JpaRepository interface and a small @Service class save and read blog posts with no SQL. Follow one save and one read through every layer, then prove it with a test.
Entities and H2 in Spring Boot: a Post Class Becomes a Table
The blog's cards are typed into HTML. A Post class with @Entity and @Id becomes the POST table in an in-memory H2 database: three pom lines, a few YAML settings, and Hibernate writes the create table SQL at startup.
Seed Data and Posts on the Homepage: CommandLineRunner, the Model and th:each
SeedData, a CommandLineRunner, saves three posts when the POST table is empty. HomeController puts postService.getAll() into the Model, and one postCard inside th:each becomes three cards. Three inserts at startup, one select per visit.
Pagination and Sorting on a Spring Boot Homepage: PageRequest In, Page Out
Eight posts, three to a page, newest first. HomeController turns ?page=1&sort=oldest into a PageRequest, PostService passes it to findAll(Pageable), H2 runs one select with an offset and one count, and the Page that comes back knows it is page 2 of 3.
