Issue
I have the following method:
@Transactional
public Store handle(Command command) {
Store store= mapper.map(command.getStoreDto(), Store.class);
Store persistedStore = storeService.save(store);
addressService.saveStoreAddress(store, command.getEmployeeId()); //this method is not crucial, should be called independently and in another transaction, without any rollback in case of exception
return persistedStore;
}
addressService.saveStoreAddress
is not crucial - when this method will throw any exception, store should be saved anyway (storeService.save(store);
). What is the best solution in my case?
Solution
Use @Transactional(propagation=REQUIRES_NEW)
on the saveStoreAddress()
such that it will execute in a new and separate transaction.
To prevent the transaction of the handle()
will be rollback because of the exception throw from saveStoreAddress()
, you also have to try-catch when calling saveStoreAddress()
.
In the end , it looks something like:
@Service
public class AddressService {
@Transactional(propagation=REQUIRES_NEW)
public void saveStoreAdress(.....){
}
}
@Transactional
public Store handle(Command command) {
.......
try{
addressService.saveStoreAddress(store, command.getEmployeeId());
}catch (Exception ex){
/***
* handle the exception thrown from saveStoreAddress.
* If you want the current transaction not rollback just because of the
* exception throw from saveStoreAddress(), do not re-throw the exception when
* handling this exception
*/
}
return ....;
}
Answered By - Ken Chan