我正在构建一个交易应用程序。该应用程序迭代超过 1400 只股票,对于每只股票,从数据库中读取价格。阅读价格后,我做了一个entityManager.clear((,以便清空持久性上下文。如果没有clear((,系统就会变得非常慢。 我从从数据库中读取的实体(InstrumentPrice(创建新的java对象(DatePrice(
然后,在 DatePrice 对象列表上执行计算,然后将这些计算存储在另一个数据库表中。 但此数据库表中未保存任何内容。
当我删除 entityManager.clear(( 时,计算将保存在表中,但应用程序变得不可接受的缓慢。
为什么 entityManager.clear(( 会影响新的事务?
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);
}
类仪器价格道
@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);
}
类计算道
@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();