简体   繁体   English

SpringBoot中@transactional注解的实时用途是什么?

[英]What is the Realtime uses of @transactional annotation in SpringBoot?

I don not have any clear concept why we use @transactional annotation.我没有任何明确的概念为什么我们使用@transactional 注释。 My need a realtime concept for use this.我需要一个实时概念来使用它。

Please give me clear concept with example on this.请给我一个清晰的概念和例子。

A transaction is a series of operations which either all occur or nothing occurs.事务是一系列操作,要么全部发生,要么什么都不发生。 In database systems you can therefore start a transaction, then execute a series of queries and then either commit the transaction if all the queries were successful or rollback if you had an error.因此,在数据库系统中,您可以启动一个事务,然后执行一系列查询,然后如果所有查询都成功则提交事务,或者如果出现错误则回滚。 During the transaction all the changes are only visible for you session and in case of a rollback all the changes you have made will be undone.在交易期间,所有更改仅对您可见 session 并且在回滚的情况下,您所做的所有更改都将被撤消。

As a real world example you could take a money transfer from one account to another.作为一个真实世界的例子,您可以将资金从一个帐户转移到另一个帐户。 There is one query to withdraw from an account and another query to credit the money to the other account.有一个查询是从一个帐户中提款,另一个查询是将钱存入另一个帐户。 If you would execute those queries without a transaction and the second query fails for whatever reason, the money would have been withdrawn from one account but not credited to another, which means you would have eliminated money.如果您在没有交易的情况下执行这些查询,而第二个查询由于某种原因失败了,那么钱会从一个帐户中提取但不会存入另一个帐户,这意味着您已经消除了钱。

Spring built an abstraction layer for that with the @Transactional annotation, which starts a transaction before you method is called and commits it if all was fine or does a rollback when an exception was thrown. Spring 使用@Transactional注释为此构建了一个抽象层,它在调用方法之前启动一个事务,如果一切正常则提交它,或者在抛出异常时进行回滚。

public class MoneyTransferService {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Transactional
    public void transferMoney(Double amount, Integer debitAccount, Integer creditAccount) {

        jdbcTemplate.update("UPDATE accounts SET balance = balance - ? where accountId = ?", amount, debitAccount);
        jdbcTemplate.update("UPDATE accounts SET balance = balance + ? where accountId = ?", amount, creditAccount);

    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM