我在Spring启动应用程序中有以下配置。我从Repository层和Service层抛出RuntimeException来查看事务处理。当我从存储库层抛出RuntimeException时,事务将被回滚,但是,如果我从Service层抛出Runtime异常,如下所示,事务不会被回滚并且数据被保存到数据库中。有人能帮我解决以下配置有什么问题吗?
- Python 3.6.5 (32-bit) on Windows 10 Pro
- Excel 2013 (German)
并且,以下是我的控制器类配置
@Configuration
@SpringBootApplication
@EnableAsync
@EnableScheduling
@ComponentScan(basePackages = { "com.abc.xyz.api.config", Constant.BASE_PACKAGE, com.abc.c4s.util.Constant.BASE_PACKAGE })
@EnableAutoConfiguration(exclude = { JndiConnectionFactoryAutoConfiguration.class, DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class, JpaRepositoriesAutoConfiguration.class,
DataSourceTransactionManagerAutoConfiguration.class })
@PropertySources({
@PropertySource(value = "classpath:jdbc.properties")
})
@EnableTransactionManagement
public class ProjectManagerApplication {
public static ConfigurableApplicationContext context;
private static final Logger logger = LoggerFactory.getLogger(ProjectManagerApplication.class);
public static ConfigurableApplicationContext startServer() throws Exception {
logger.debug("Starting server");
SpringApplicationBuilder builder = new SpringApplicationBuilder(ProjectManagerApplication.class);
builder.headless(false);
context = builder.run(new String[] {});
logger.debug("Server started - " + (context != null ? context.isRunning() : "context null, starting failed"));
return context;
}
}
这是我的服务类。
@RestController
public class RWSettingsController {
@Autowired
SettingsService rwSettingsService;
@RequestMapping(value = "/api/settings", method = RequestMethod.POST)
public void createKiosk(@RequestBody SettingsDTO settingDTO) throws ABCInternalException, ABCException {
//try{
settingsService.create(settingDTO);
//}catch (Exception e){
// e.printStackTrace();
// }
}
}
}
我的存储库类如下
@Service
@Transactional//(propagation = Propagation.SUPPORTS, readOnly = true)
public class SettingsService {
@Autowired
SettingsRepository settingsRepository;
@Autowired
ModelMapper modelMapper;
private static final Logger logger = LoggerFactory.getLogger(SettingsService.class);
// @Transactional(
// propagation = Propagation.REQUIRED,
// readOnly = false)
public void create(SettingsDTO settingsDTO) throws ButterflyInternalException, ButterflyException {
try{
SettingsModel settingsModel = new SettingsModel ();
settingsModel .setActive(true);
settingsModel .setParameterDescription(settingsDTO.getParameterDescription());
settingsModel .setParameterName(settingsDTO.getParameterName());
settingsModel .setParameterValue(settingsDTO.getParameterValue());
//throw new HibernateException("");
rwsSettingsRepository.create(rwsKioskSettingsBPA);
throw new RuntimeException("");
}catch(ABCException e){
logger.error(e.getMessage(),e);
throw e;
}catch(Exception e){
logger.error(e);
throw e;
}
}
答案 0 :(得分:0)
我发现这种行为背后的原因是什么。如果应用程序抛出运行时异常,则Spring引导回滚事务。在我的服务层中,我捕获运行时异常并抛出特定于应用程序的异常,这就是spring不回滚事务的原因。因此,在更改代码以抛出最初生成的相同运行时异常后,应用程序成功回滚了事务。
如果我把它放在服务层中,上面的代码就会运行 @Transactional(rollbackFor = Exception.class)