What is the difference between Java's @Transactional(rollbackFor = Exception.class) and @Transactional()?

@Transactional(rollbackFor = Exception.class)and @Transactional()are annotations used for transaction management in the Spring framework, and they have the following differences:

  1. @Transactional(rollbackFor = Exception.class)

    • The parameter is used rollbackForto specify that the transaction rollback occurs when an exception of the specified type is encountered.
    • rollbackFor = Exception.classIndicates that transaction rollback will be triggered when any type of exception is encountered.
    • This means that no matter what type of exception is encountered, including runtime exceptions and checked exceptions, a transaction rollback will be triggered.
  2. @Transactional()

    • The parameter is not specified , so by default a transaction rollback will rollbackForonly be triggered if a runtime exception ( ) or an exception of type Error is encountered .RuntimeException
    • For checked exceptions (Checked Exception), transaction rollback is not triggered by default.
    • If a checked exception is thrown within the method body, the transaction will continue to commit rather than rollback.

Summarize:

  • @Transactional(rollbackFor = Exception.class)The rollback strategy is specified, no matter what type of exception is encountered, the transaction rollback will be triggered.
  • @Transactional()By default, transaction rollback is only triggered when a runtime exception or Error type exception is encountered, and rollback is not triggered by default for checked exceptions.

In practical applications, according to business requirements and exception handling strategies, you can choose to use appropriate @Transactionalannotations to manage transactions and specify appropriate rollback behaviors.

Guess you like

Origin blog.csdn.net/liuruiaaa/article/details/130941596