basil_benny
basil_benny

Reputation: 23

@Transactional does not work if exception is thrown

This is my spring boot application:

@SpringBootApplication
@EnableTransactionManagement(proxyTargetClass=true) 
public class WhizhopApplication {

public static void main(String[] args) {
    
    SpringApplication.run(WhizhopApplication.class, args);
 }
}

This is my service:

@Service
public class OrderService {
  @Autowired
   BillRepository billRepo;

    @Transactional(rollbackFor = Exception.class)
    public BaseDTO saveKot(BillDTO billDto) {
     try {
        //business logic
        billRepo.save();
     } catch (Exception e) {
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        
    }
   }
}

If any exception occurs, the transaction is not rolled back.

Upvotes: 1

Views: 3278

Answers (3)

Almas Abdrazak
Almas Abdrazak

Reputation: 3612

By default rollback from @Transactional is happen only for Runtime execption, if you want to change this behavior you can add rollBackFor parameter to annotation

@Transactional(rollbackFor={MyException.class})

Upvotes: 0

Justinas Jakavonis
Justinas Jakavonis

Reputation: 8798

You shouldn't catch exception if you want it to be processed with @Transactional.

Also please note that:

  1. @Transactional works only for public methods
  2. Spring’s @Transactional does not rollback on checked exceptions

Upvotes: 2

Nikolai
Nikolai

Reputation: 785

Extract business logic into separate method annotated by @Transactional(rollbackFor = Exception.class) and remove annotation from saveKot.

public BaseDTO saveKot(BillDTO billDto) {
    try {
        businessLogic(billDto);
    } catch (Exception e) {
        // catch if it needed but manually rollback is not needed
        return null;
    }
}

@Transactional(rollbackFor = Exception.class)
BaseDTO businessLogic(BillDTO billDto) throws Exception {
    // It will be automatically rolled back if Exception occurs
    ...
}

Upvotes: 0

Related Questions