WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Spring Boot & Hibernate · Intermediate · question 29 of 100

How can you handle database transactions in a Spring Boot application using Hibernate?

📕 Buy this interview preparation book: 100 Spring Boot & Hibernate questions & answers — PDF + EPUB for $5

In a Spring Boot application that uses Hibernate for database access, transactions can be managed using Spring’s @Transactional annotation.

The @Transactional annotation is used to demarcate a method or a class with transactional semantics. When a method or a class is marked with @Transactional, Spring will manage transactions for that method or class. Spring Boot will automatically create a transaction manager if it detects a DataSource on the classpath, which is typically the case when using Hibernate.

Here is an example of using @Transactional with Hibernate in a Spring Boot application:

    @Service
    public class UserService {
        @Autowired
        private UserRepository userRepository;
        
        @Transactional
        public void saveUser(User user) {
            userRepository.save(user);
        }
        
        @Transactional(readOnly = true)
        public List<User> getUsers() {
            return userRepository.findAll();
        }
    }

In this example, we have a UserService class that is marked with @Service, indicating that it is a Spring-managed service. We have injected a UserRepository instance using Spring’s @Autowired annotation, which is a Spring Data JPA repository.

The saveUser method is marked with @Transactional, indicating that it should be executed within a transaction. When this method is called, Spring will automatically begin a transaction before the method is executed, and commit the transaction after the method has completed successfully. If an exception is thrown, Spring will roll back the transaction.

The getUsers method is also marked with @Transactional, but with the readOnly attribute set to true. This indicates that this method will not modify the database, and can be executed with read-only access. By setting readOnly to true, Spring can optimize the transaction by not flushing changes to the database at the end of the transaction.

Overall, using @Transactional with Hibernate in a Spring Boot application is a powerful and convenient way to manage transactions. It allows developers to focus on writing business logic and leave the transaction management to Spring.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Spring Boot & Hibernate interview — then scores it.
📞 Practice Spring Boot & Hibernate — free 15 min
📕 Buy this interview preparation book: 100 Spring Boot & Hibernate questions & answers — PDF + EPUB for $5

All 100 Spring Boot & Hibernate questions · All topics