What does @Transactional do?

java, spring, spring-jdbc, transactions

Solution

You can handle your `Transactions` in two ways: `Programmatically` and `Declarative`.

When you're using `transaction.begin` and `transaction.commit` and ..., you are hanling your `Transactions` programmatically. This way you have more control on your `Transaction` boundaries but you will end up with lots of similar codes (`Cross Cutting Concerns`) scattered all over your project.

But in `Declarative` way, the codes that handle the `Transactions` are separated from your businesses logic and will not be scattered all over your project. It's one of the main concepts of `Aspect Oriented Programming`.

Problem

I know this is probably a duplicate and, ironically, before I started reading here and there about it, I thought I knew what it was for (needless to say but I'll still say it, please correct me where I am wrong): It relieves the programmer of having to use `transaction.begin()` and `commit()`. If you have a method that calls two DAO methods which normally would each have a `transaction.begin` and `transaction.commit` encompassing the real operations and call them it would result in two transactions ( and there might be rollback issues if the previous DAO method was supposed to be rolled-back too). But if you use `@transactional` on your method then all those DAO calls will be wrapped in a single `begin()`- `commit()` cycle. Of course, in case you use `@Transactional` the DAOs must not use the `begin()` and `commit()` methods I think.

Original source

Related problems