Reputation: 87
I have Spring Boot (v2.4.1) application with Hibernate and JpaRepository like Dao. Here is code:
import javax.transaction.Transactional;
@Service
public class SomeService {
public void executeJob(){
executeJob(1L);
}
@Transactional
public void executeJob(Long carId){
Car car = carDao.findById(carId);
car.setStatus("Destroyed");
carDao.save(car);
throw new Exception();
}
}
So, after exception throwing, I expect that transaction will be rollbacked and car will not be updated in DB. But it's not.
I turned in logs and find out, that JpaTransactionManager opens and commits transaction two times. First time for carDao.findById(carId). Second time for carDao.save(car).
And it seems the cause of missing transaction rollback.
I suppose that it could be related with hibernate flush mechanism. But spring.jpa.properties.org.hibernate.flushMode=NEVER is not working too...
Any ideas? Thanks.
Upvotes: 0
Views: 902
Reputation: 1080
The transaction was not rolled back because Spring by default not rollbacks when checked exceptions are thrown.
So, you have two options:
1 - Change your exception to an unchecked exception (extends RuntimeException)
2 - Forces Spring to rollback a checked exception.
If you choose the second option, your code will look like this:
import org.springframework.transaction.annotation.Transactional;
@Service
public class SomeService {
@Transactional(rollbackFor = Exception.class)
public void executeJob() {
executeJob(1L);
}
@Transactional(rollbackFor = Exception.class)
public void executeJob(Long carId) {
Car car = carDao.findById(carId);
car.setStatus("Destroyed");
carDao.save(car);
throw new Exception();
}
}
Upvotes: 2