Reputation:
I'm learning about how to create REST API with JPA and Hibernate and a MySQL database and I see this @Transactional
annotation. Can someone explain what is the use of this annotation?
For example I have this simple DAO class:
@Repository
public class EmployeeDAOHibernateImpl implements EmployeeDAO {
// define field for entitymanager
private EntityManager entityManager;
// set up constructor injection
@Autowired
public EmployeeDAOHibernateImpl(EntityManager entityManager) {
this.entityManager = entityManager;
}
@Override
@Transactional
public List<Employee> findAll() {
// get the current hibernate session
Session currentSession = entityManager.unwrap(Session.class);
// create a query
Query<Employee> theQuery =
currentSession.createQuery("from Employee", Employee.class);
// execute query and get result list
List<Employee> employees = theQuery.getResultList();
// return the results
return employees;
}
}
You can see the @Transactional
used for findAll()
method, but if I delete this @Transactional
I get the same output... then what is the use of this @Transactional
?
Upvotes: 42
Views: 99570
Reputation: 3021
@Transactional
annotation is used when you want the certain method/class(=all methods inside) to be executed in a transaction.
Let's assume user A
wants to transfer 100$ to user B
. What happens is:
Let's assume the exception is thrown after succeeding 1)
and before executing 2)
. Now we would have some kind of inconsistency because A
lost 100$ while B
got nothing.
Transactions means all or nothing. If there is an exception thrown somewhere in the method, changes are not persisted in the database. Something called rollback
happens.
If you don't specify @Transactional
, each DB call will be in a different transaction.
Upvotes: 97
Reputation: 26926
Generally the @Transactional
annotation is written at the service level.
It is used to combine more than one writes on a database as a single atomic operation.
When somebody call the method annotated with @Transactional
all or none of the writes on the database is executed.
In the case of read operations it is not useful and so it is in case of a single atomic write. You are using it in a single read (select) so adding or removing the @Transactional
annotation has no impact.
Upvotes: 55