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);
}
}
Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!