Spring 引导 - 如何在事务范围之外调用另一个方法
Spring Boot - how to call another method outside of the transaction scope
我有以下方法:
@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
并不重要 - 当此方法抛出任何异常时,无论如何都应保存存储 (storeService.save(store);
)。对我来说最好的解决方案是什么?
在 saveStoreAddress()
上使用 @Transactional(propagation=REQUIRES_NEW)
,这样它将在一个新的单独事务中执行。
为了防止 handle()
的事务因为 saveStoreAddress()
抛出的异常而回滚,调用 saveStoreAddress()
.[=17= 时也需要 try-catch ]
最后,看起来像这样:
@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 ....;
}
我有以下方法:
@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
并不重要 - 当此方法抛出任何异常时,无论如何都应保存存储 (storeService.save(store);
)。对我来说最好的解决方案是什么?
在 saveStoreAddress()
上使用 @Transactional(propagation=REQUIRES_NEW)
,这样它将在一个新的单独事务中执行。
为了防止 handle()
的事务因为 saveStoreAddress()
抛出的异常而回滚,调用 saveStoreAddress()
.[=17= 时也需要 try-catch ]
最后,看起来像这样:
@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 ....;
}