user9608350
user9608350

Reputation:

What is the use of @Transactional with JPA and Hibernate?

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

Answers (2)

Pijotrek
Pijotrek

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:

  1. We decrease A's account by 100$
  2. We add 100$ to B's account

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

Davide Lorenzo MARINO
Davide Lorenzo MARINO

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

Related Questions