I study Hibernate.
I understand that the transaction ensures that either all the data of this transaction will be saved or not. Then it is logical to use transactions for operations related to the addition / updating of data in the database. Why then should I use the @Transactional annotation to perform a SELECT ? For example:
UserDAO:
public class UserDAO { private SessionFactory sessionFactory; public String getNameByUserId(int userId) { Session session = sessionFactory.getCurrentSession(); Query query = session.createQuery("select u.name from User u where u.id=:userId"); ... ... return name; } } UserService:
public class UserService { private UserDAO userDAO; @Transactional public String getNameByUserId(int userId) { return userDAO.getNameByUserId(userId); } } UPD:
If I @Transactional , then on the line Session session = sessionFactory.getCurrentSession(); an exception will be thrown. I understand that in this case I need to do openSession() and close() manually? How does getCurrentSession() ?
@Transactionalyou@Transactionalover transaction management to a spring (open-close-rollback, etc.), if you don’t specify, you have to manage everything yourself.getCurrentSession()takes the current transaction and returns it, in the case of the annotation it created a spring, without it you have to deal with it yourself. - Vartlok