Senior
Have you used the @Transactional annotation in Hibernate? Tell about working with transactions.
sobes.tech AI
Answer from AI
The @Transactional annotation in Hibernate (and Spring) is used for managing transactions at the method or class level. It ensures that all database operations within the method are executed within a single transaction.
When using @Transactional:
- The transaction automatically starts when entering the method.
- If the method completes successfully, the transaction is committed.
- If an unchecked exception (runtime exception) occurs, the transaction is rolled back.
This simplifies transaction management and ensures atomicity of operations.
Example:
@Service
public class UserService {
@Transactional
public void createUser(User user) {
entityManager.persist(user);
// other database operations
}
}
Important to remember:
- Transactions should be short to avoid resource blocking.
- Inside a transaction, you can work with lazy associations without LazyInitializationException.
- When using
@Transactionalat the service level, it is better to avoid calls from within the same class (self-invocation), as Spring proxy will not work.
In Hibernate without Spring, transactions are managed manually through Session and Transaction:
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
try {
// operations
tx.commit();
} catch (Exception e) {
tx.rollback();
} finally {
session.close();
}