为什么 JPARepository.save 方法在 ExecutorService 任务中使用时不起作用?
@Component
public class Testing {
@Inject
JobSummaryRepository jobSummaryRepository;
private Logger log = LoggerFactory.getLogger(JobSummary.class);
@PostConstruct
public void Save(){
JobSummary js = new JobSummary();
js.setCount(1L);
js.setCity_id(1L);
js.setCompany_id(1L);
js.setDate(new Date());
js.setJob_master_id(1L);
js.setHub_id(1L);
js.setUser_id(1L);
js.setJob_status_id(1L);
ExecutorService executor = Executors.newFixedThreadPool(10);
Future<String> future = executor.submit(this.CallablecustomSaveOrUpdate(js));
try {
future.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (Exception e){
e.printStackTrace();
} finally {
log.info("What!!");
}
//jobSummaryRepository.save(js);
executor.shutdown();
}
private Callable<String> CallablecustomSaveOrUpdate(JobSummary js){
return () -> {
jobSummaryRepository.save(js);
return "Done";
};
}
}
上面的代码不会抛出任何错误,也不在数据库中保存任何数据。最后 block 也没有执行。
另一方面,注释掉 ExecutorService 逻辑并直接调用 jobSummaryRepository.save(js) 效果非常好。
我无法理解这个问题。
最佳答案
我认为 @PostConstruct
导致了这个问题。因为它是在加载所有 spring 组件/上下文之前调用的。
你可以使用spring的ContextRefreshedEvent为此目的。
简单示例:
@Component
public Test implements ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
//do something if all apps have initialised
}
}
希望这会起作用。
关于java - 与 ExecutorService 一起使用时,Hibernate 不会抛出任何错误,也不会将记录保存在数据库中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54311301/