I don not have any clear concept why we use @transactional annotation. 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.
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.
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);
}
}