0% found this document useful (0 votes)
4 views

Spring Transaction Management

Uploaded by

karunjsiruthai
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Spring Transaction Management

Uploaded by

karunjsiruthai
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

Spring Transaction Management -→

Transaction Sucessfull

Commit

Initial

State Transaction

Transaction Failed

RollBack

An important aspect of transaction management is defining the right


transaction boundary, when should a transaction start, when should it
end, when data should be committed in DB and when it should be rolled
back (in the case of exception).
There are specifically two approaches to manage the transaction :

1)Legacy Way To manage the transactions:

try{
1) begin transaction
2) own business logic
3) commit transaction
}
catch(Exception){
rollback transaction
throw exception
}
Pros:

• The scope of the transaction is very clear in the code.

Cons:

• It's repetitive and error-prone.


• Any error can have a very high impact.
• A lot of boilerplate needs to be written and if you want to call
another method from this method then again you need to manage
it in the code.

2) Use Spring to manage the transactions

Pros:

Lightweight declarative syntax

Flexible transaction propagation

Automatic rollback in the case of exceptions

Here we use @Transactional Annotation for the Spring transaction


Management

The @Transactional annotation is used to mark a method or a class as


transactional, meaning that any database operations performed within the
marked method or class will be executed within a transaction. If the
transaction is successful, the changes will be committed to the database.
Example:

In the repository you find the example Where there are the two
repositories Patient and Appointment

When you trying to save the appointment after patient and that time If the
excpetion occurs then the whole transaction will rollback even the patient
data also.

Curl --curl --location 'http://localhost:8080/bookappointment' \

--header 'Content-Type: application/json' \


--data '{
"name":"s",
"gender":"male",
"mobile":"988812922",
"age":24
}'

You might also like