CodexBloom - Programming Q&A Platform

Handling SQLException in Java with Spring Data JPA: Transactions Not Rolling Back

👀 Views: 50 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-01
java spring-boot jpa Java

I'm deploying to production and Quick question that's been bugging me - I'm relatively new to this, so bear with me... I'm currently working with an scenario where transactions are not rolling back as expected when a `SQLException` occurs in my Spring Data JPA application. I'm using Spring Boot 2.6.3 and Hibernate 5.6.0. I've annotated my service method with `@Transactional`, but it seems that the transaction is still committed even when an exception is thrown. Here's the relevant code: ```java @Service public class UserService { @Autowired private UserRepository userRepository; @Transactional public void addUser(User user) { userRepository.save(user); // Simulate a database behavior if (user.getName() == null) { throw new SQLException("User name want to be null"); } } } ``` When I invoke this method with a user who has a null name: ```java userService.addUser(new User(null)); ``` I expect the transaction to roll back, but the data is still being persisted in the database. The exception message I see in the logs is `SQLException: User name want to be null`, but it doesn't trigger a rollback. I've also checked my configuration in `application.properties` and it includes: ```properties spring.jpa.hibernate.ddl-auto=update spring.datasource.url=jdbc:mysql://localhost:3306/mydb spring.datasource.username=root spring.datasource.password=root ``` I suspect it might have something to do with the exception type not being a runtime exception. I tried changing the method to throw a `RuntimeException` instead, and that does trigger a rollback, but I want to understand why `SQLException`, which is checked, does not. Is there a way to configure Spring to roll back on checked exceptions like `SQLException`? Any insights or best practices would be greatly appreciated. I'd really appreciate any guidance on this. I'm working in a CentOS environment. This issue appeared after updating to Java 3.10. Am I approaching this the right way?