๐๐ SPRING CERTIFICATION QUESTION: What is the default rollback policy? How can you override it?
๐๐ SPRING CERTIFICATION QUESTION: What is the default rollback policy? How can you override it?
โ๐ซ Answer:
The default rollback policy is defined by DefaultTransactionAttribute
which states that rollback should be performed only โผ๏ธ in case of RuntimeException and Error โ but not on checked exceptions.
This default behavior can be overridden using (in case a declarative approach is used):
- Transactional#noRollbackFor()
- Transactional#noRollbackForClassName()
- Transactional#rollbackFor()
- Transactional#rollbackForClassName()
annotation attributes.
#spring #certificationquestion #vcp
Transaction Rollback ๐ https://lnkd.in/gbTBtG6W
The @Transactional annotation is the metadata that specifies the semantics of the transactions on a method.
We have two ways to roll back a transaction: declarative and programmatic.
In the declarative approach, we annotate the methods with the @Transactional annotation.
The @Transactional annotation makes use of the attributes rollbackFor or rollbackForClassName to rollback the transactions,
and the attributes noRollbackFor or noRollbackForClassName to avoid rollback on listed exceptions.
The default rollback behavior in the declarative approach will roll back โฉ๏ธon runtime exceptions.
1๏ธโฃ Let's see a simple example using the declarative approach to rollback a transaction for runtime exceptions or errors:
@๐๐ซ๐๐ง๐ฌ๐๐๐ญ๐ข๐จ๐ง๐๐ฅ
๐ฉ๐ฎ๐๐ฅ๐ข๐ ๐ฏ๐จ๐ข๐ ๐๐ซ๐๐๐ญ๐๐๐จ๐ฎ๐ซ๐ฌ๐๐๐๐๐ฅ๐๐ซ๐๐ญ๐ข๐ฏ๐๐๐ข๐ญ๐ก๐๐ฎ๐ง๐ญ๐ข๐ฆ๐๐๐ฑ๐๐๐ฉ๐ญ๐ข๐จ๐ง(๐๐จ๐ฎ๐ซ๐ฌ๐ ๐๐จ๐ฎ๐ซ๐ฌ๐) {
๐๐จ๐ฎ๐ซ๐ฌ๐๐๐๐จ.๐๐ซ๐๐๐ญ๐(๐๐จ๐ฎ๐ซ๐ฌ๐);
๐ญ๐ก๐ซ๐จ๐ฐ ๐ง๐๐ฐ ๐๐๐ญ๐๐๐ง๐ญ๐๐ ๐ซ๐ข๐ญ๐ฒ๐๐ข๐จ๐ฅ๐๐ญ๐ข๐จ๐ง๐๐ฑ๐๐๐ฉ๐ญ๐ข๐จ๐ง("๐๐ก๐ซ๐จ๐ฐ๐ข๐ง๐ ๐๐ฑ๐๐๐ฉ๐ญ๐ข๐จ๐ง ๐๐จ๐ซ ๐๐๐ฆ๐จ๐ข๐ง๐ ๐๐จ๐ฅ๐ฅ๐๐๐๐ค!!!");
}
2๏ธโฃ Next, we'll use the declarative approach to roll back a transaction for the listed checked exceptions.
The rollback e is on SQLException:
@๐๐ซ๐๐ง๐ฌ๐๐๐ญ๐ข๐จ๐ง๐๐ฅ(๐ซ๐จ๐ฅ๐ฅ๐๐๐๐ค๐ ๐จ๐ซ = { ๐๐๐๐๐ฑ๐๐๐ฉ๐ญ๐ข๐จ๐ง.๐๐ฅ๐๐ฌ๐ฌ })
๐ฉ๐ฎ๐๐ฅ๐ข๐ ๐ฏ๐จ๐ข๐ ๐๐ซ๐๐๐ญ๐๐๐จ๐ฎ๐ซ๐ฌ๐๐๐๐๐ฅ๐๐ซ๐๐ญ๐ข๐ฏ๐๐๐ข๐ญ๐ก๐๐ก๐๐๐ค๐๐๐๐ฑ๐๐๐ฉ๐ญ๐ข๐จ๐ง(๐๐จ๐ฎ๐ซ๐ฌ๐ ๐๐จ๐ฎ๐ซ๐ฌ๐) ๐ญ๐ก๐ซ๐จ๐ฐ๐ฌ ๐๐๐๐๐ฑ๐๐๐ฉ๐ญ๐ข๐จ๐ง {
๐๐จ๐ฎ๐ซ๐ฌ๐๐๐๐จ.๐๐ซ๐๐๐ญ๐(๐๐จ๐ฎ๐ซ๐ฌ๐);
๐ญ๐ก๐ซ๐จ๐ฐ ๐ง๐๐ฐ ๐๐๐๐๐ฑ๐๐๐ฉ๐ญ๐ข๐จ๐ง("๐๐ก๐ซ๐จ๐ฐ๐ข๐ง๐ ๐๐ฑ๐๐๐ฉ๐ญ๐ข๐จ๐ง ๐๐จ๐ซ ๐๐๐ฆ๐จ๐ข๐ง๐ ๐ซ๐จ๐ฅ๐ฅ๐๐๐๐ค");
}
3๏ธโฃ Let's see a simple use of attribute noRollbackFor in the declarative approach to prevent rollback of the transaction for the listed exception:
@๐๐ซ๐๐ง๐ฌ๐๐๐ญ๐ข๐จ๐ง๐๐ฅ(๐ง๐จ๐๐จ๐ฅ๐ฅ๐๐๐๐ค๐ ๐จ๐ซ = { ๐๐๐๐๐ฑ๐๐๐ฉ๐ญ๐ข๐จ๐ง.๐๐ฅ๐๐ฌ๐ฌ })
๐ฉ๐ฎ๐๐ฅ๐ข๐ ๐ฏ๐จ๐ข๐ ๐๐ซ๐๐๐ญ๐๐๐จ๐ฎ๐ซ๐ฌ๐๐๐๐๐ฅ๐๐ซ๐๐ญ๐ข๐ฏ๐๐๐ข๐ญ๐ก๐๐จ๐๐จ๐ฅ๐ฅ๐๐๐๐ค(๐๐จ๐ฎ๐ซ๐ฌ๐ ๐๐จ๐ฎ๐ซ๐ฌ๐) ๐ญ๐ก๐ซ๐จ๐ฐ๐ฌ ๐๐๐๐๐ฑ๐๐๐ฉ๐ญ๐ข๐จ๐ง {
๐๐จ๐ฎ๐ซ๐ฌ๐๐๐๐จ.๐๐ซ๐๐๐ญ๐(๐๐จ๐ฎ๐ซ๐ฌ๐);
๐ญ๐ก๐ซ๐จ๐ฐ ๐ง๐๐ฐ ๐๐๐๐๐ฑ๐๐๐ฉ๐ญ๐ข๐จ๐ง("๐๐ก๐ซ๐จ๐ฐ๐ข๐ง๐ ๐๐ฑ๐๐๐ฉ๐ญ๐ข๐จ๐ง ๐๐จ๐ซ ๐๐๐ฆ๐จ๐ข๐ง๐ ๐ซ๐จ๐ฅ๐ฅ๐๐๐๐ค");
}