Spring Boot: Transactions Management with JDBCTemplate Example


In Spring Boot with JdbcTemplate, transactions can be managed using the TransactionTemplate or by using the @Transactional annotation.

Example:
@Component
public class EmployeeService {

    private final JdbcTemplate jdbcTemplate;
    private final TransactionTemplate transactionTemplate;

    public EmployeeService(JdbcTemplate jdbcTemplate, PlatformTransactionManager transactionManager) {
        this.jdbcTemplate = jdbcTemplate;
        this.transactionTemplate = new TransactionTemplate(transactionManager);
    }

    public void transferSalary(int employeeId1, int employeeId2, int amount) {
        transactionTemplate.execute(status -> {
            try {
                jdbcTemplate.update("UPDATE employee SET employeeSalary = employeeSalary - ? WHERE employeeId = ?", amount, employeeId1);
                jdbcTemplate.update("UPDATE employee SET employeeSalary = employeeSalary + ? WHERE employeeId = ?", amount, employeeId2);
                return true;
            } catch (Exception e) {
                status.setRollbackOnly();
                return false;
            }
        });
    }
}

In the above example, we have a transferSalary method that transfers an amount from one employee to another. The method is wrapped in a transactionTemplate.execute() call, which manages the transaction.

If an exception is thrown during the transaction, the transaction will be rolled back.



We can also use the @Transactional annotation to manage transactions.
@Service
@Transactional
public class EmployeeService {

    private final JdbcTemplate jdbcTemplate;

    public EmployeeService(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    public void transferSalary(int employeeId1, int employeeId2, int amount) {
        jdbcTemplate.update("UPDATE employee SET employeeSalary = employeeSalary - ? WHERE employeeId = ?", amount, employeeId1);
        jdbcTemplate.update("UPDATE employee SET employeeSalary = employeeSalary + ? WHERE employeeId = ?", amount, employeeId2);
    }
}

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap