Reputation: 23
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
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
Reputation: 8798
You shouldn't catch exception if you want it to be processed with @Transactional
.
Also please note that:
@Transactional
works only for public methods Upvotes: 2
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