Hibernate在执行时未运行插入和更新

时间:2018-12-11 12:11:04

标签: spring hibernate jpa spring-data-jpa

{
  "extends": "./tsconfig.es5.json",
  "compilerOptions": {
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "outDir": "../out-tsc/spec",
    "module": "commonjs",
    "types": [
      "jasmine",
      "node"
    ]
  },
  "files": [
    "test.ts",
    "polyfills.ts"
  ],
  "include": [
    "**/*.spec.ts",
    "**/*.d.ts"
  ]
}

如您所见,我想为发票设置所有更正,然后从数据库中重新加载它们以生成XLSX文件。

问题是@Transactional public long generateInvoice(...) { final InvoiceEntity invoice = new InvoiceEntity(...); final InvoiceEntity dbInvoice = invoiceService.save(invoice); List<CorrectionEntity> corrections = correctionService.findAllByVendor(...); corrections.forEach(correction -> correction.setInvoice(dbInvoice)); correctionService.saveAll(corrections); InvoiceEntity finalDBInvoice = invoiceService.getInvoiceById(dbInvoice.getId()).orElseThrow(IllegalStateException::new); documentService.generateExcel(finalDBInvoice); return dbInvoice.getId(); } 中的数据不可用,因为根据我在日志中注意到的,finalDBInvoiceINSERT在结束时执行方法,可能是因为UPDATE。当我要生成Excel文件时,@Transactional字段为corrections

从我的角度来看,我期望它能够正常工作。使用JDBC之类的东西会起作用,因为每个语句将在正确的时间在单个事务中执行。

null

1 个答案:

答案 0 :(得分:0)

您是对的。方法末尾的休眠提交事务。您有两个选择: 1.分别保存和读取数据以两种方法生成excel,然后依次调用它们。 2.插入或保存后使用冲洗方法。像这样:

//correct
@Transactional
public long generateInvoice(...) {
    final InvoiceEntity invoice = new InvoiceEntity(...);

    final InvoiceEntity dbInvoice = invoiceService.save(invoice);
    invoiceService.flush();

    List<CorrectionEntity> corrections = correctionService.findAllByVendor(...);
    corrections.forEach(correction -> correction.setInvoice(dbInvoice));
    correctionService.saveAll(corrections);

    InvoiceEntity finalDBInvoice = invoiceService.getInvoiceById(dbInvoice.getId()).orElseThrow(IllegalStateException::new);

    documentService.generateExcel(finalDBInvoice);

    return dbInvoice.getId();

}