我正在构建一个交易应用程序。该应用程序迭代超过 1400 只股票,并且对于每只股票,价格都是从数据库中读取的。阅读价格后,我执行了entityManager.clear(),以便清空持久性上下文。如果没有clear(),系统会变得极其缓慢。 我从从数据库读取的实体 (InstrumentPrice) 创建新的 java 对象 (DatePrice)
然后,对 DatePrice 对象列表进行计算,然后将这些计算结果存储在另一个数据库表中。但是这个数据库表中没有保存任何内容。
当我删除entityManager.clear()时,计算结果将保存在表中,但应用程序变得慢得令人无法接受。
为什么entityManager.clear()会影响新的Transaction?
public void performCalculation(TaRequestDto taRequestDto, Stock stock) throws Exception {
List<InstrumentPrice> instrumentPriceList = instrumentPriceDao.getPricesBetweenDates(stock, taRequestDto.getDateFrom(), taRequestDto.getDateTo());
List<DatePrice> datePriceList = InstrumentPriceUtil.convertInstrumentPriceListToDatePriceList(instrumentPriceList);
calculationService.execute(datePriceList, stock);
}
InstrumentPriceDao 类
@Transactional(propagation = Propagation.REQUIRES_NEW)
public List<InstrumentPrice> getPricesBetweenDates(Stock stock, LocalDate dateFrom, LocalDate dateTo) {
List<InstrumentPrice> instrumentPriceList;
instrumentPriceList = getPriceForAllStocksBetweenDates(dateFrom, dateTo);
entityManager.clear();
return instrumentPriceList;
}
类计算服务
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void execute(List<DatePrice> datePriceList, Stock stock) throws Exception {
// do some calculations
List(Double) calculatedValues = ........
calculationDao.insertCalculations(stock, calculatedValues);
}
计算Dao类
@Override
@Transactional(propagation = Propagation.MANDATORY)
public calculation insertCalculations(Stock stock, List<Double> calculatedValues ) {
Calculation = new Calculation();
// setting properties ...
return entityManager.persist(calculation);
}
最佳答案
所以你做了一个清除,这意味着你从持久化上下文中删除了所有实体。 https://docs.oracle.com/javaee/7/api/javax/persistence/EntityManager.html#clear--
“清除持久化上下文,导致所有托管实体分离。对尚未刷新到数据库的实体所做的更改将不会被持久化。”
之前进行刷新,这会将您的更改写入数据库: https://docs.oracle.com/javaee/7/api/javax/persistence/EntityManager.html#flush--
“将持久化上下文同步到底层数据库。”
entityManager.flush();
entityManager.clear();
关于java spring jpa使用entityManager.clear()时没有在数据库表中保存任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57963780/