How to use Sprint transactional annotation

  1. How to use Sprint transactional annotation
  2. 1. Attributes
  3. 2. Transaction Override

How to use Sprint transactional annotation

1. Attributes

  • value and transactionManager
    • used to provide a TransactionManager reference to be used when handling the transaction for the annotated block
  • propagation
    • define how the transaction boundaries propagate to other methods that will be called either directly or indirectly from within the annotated block
    • default is REQUIRED
      • means a transaction is started if no transaction is already available
      • otherwise use the current running thread
  • timeout and timeoutString
    • define the max number of seconds the current method is allowed to run
  • readOnly
    • defines if the current transaction is read-only or read-write
  • rollbackFor and rollbackForClassName
    • define one or more Throwable classes for which the current transaction will be rolled back
    • default is RuntimeException or an Error is thrown, but not for a checked Exception
  • noRollbackFor and noRollbackForClassName
    • used for one or more RuntimeException

2. Transaction Override

  • addStatementReportOperation is using the serializeble level, which override the class level readonly transaction
@Service
@Transactional(readOnly = true)
public class OperationService {

    @Transactional(isolation = Isolation.SERIALIZABLE)
    public boolean addStatementReportOperation(
        String statementFileName,
        long statementFileSize,
        int statementChecksum,
        OperationType reportType) {

        ...
    }
}
  • we use readOnly in class level because Spring could perform some read only optimization
    • we could save memory when loading read only entities since the loaded state is discarded right away, and not kept for the whole duration of the currently running persistence context
    • also, in the cluster, read only data source could be redirected to DB replica instead of DB primary, this could also reduce the burden for primary
  1. https://stackoverflow.com/questions/10394857/how-to-use-transactional-with-spring-data#:~:text=Thus we recommend using %40Transactional,re-decorated in that interface
  2. https://vladmihalcea.com/spring-read-only-transaction-hibernate-optimization/
  3. https://vladmihalcea.com/spring-transactional-annotation/

转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 stone2paul@gmail.com

文章标题:How to use Sprint transactional annotation

文章字数:289

本文作者:Leilei Chen

发布时间:2022-07-15, 20:58:18

最后更新:2022-07-15, 20:59:24

原始链接:https://www.llchen60.com/How-to-use-Sprint-transactional-annotation/

版权声明: "署名-非商用-相同方式共享 4.0" 转载请保留原文链接及作者。

目录
×

喜欢就点赞,疼爱就打赏