【问题标题】:Correctly commit to database using @Transactional in spring-data在 spring-data 中使用 @Transactional 正确提交到数据库
【发布时间】:2019-09-30 06:53:12
【问题描述】:

我有一个测试函数,它应该执行以下任务

  1. 将数据插入数据库
  2. 查询数据库并验证数据是否符合预期

问题是在我的测试中,数据还没有提交到数据库中,就像卡在transactional步骤中一样,我怎么能确定在执行第二个查询之前提交数据。

这是我测试功能的一部分,@Rollback(false) 仅用于开发阶段。

@Test
@Rollback(false)
....
reportJobManager.saveOutput(savedDef, pipeline, results, null)
reportJobManager.retryRetention(savedDef, listOf(csvDeliverbale))

保存输出函数。示例代码

@Transactional
fun saveOutput() {
    if (deliverable.type.name == "DATA_RETENTION_RESULT") {
        finishedPipeline.postProcessors.forEach {
            //it(definition, dbDeliverable)
            val dbRetention = ReportRetention(
                deliverable = dbDeliverable,
                definition = definition,
                retryCount = 1L
            )
            val retentionUploadSaved = retentionRepository.save(dbRetention)
            if (retentionUploadSaved.id == null) {
                throw IllegalStateException("Retention upload was not saved!")
            }
        }
    }
}

retryRetention功能码

fun retryRetention(definition: ReportDefinition, listOfDeliverables: List<Deliverable>) {
        retentionRepository.findAll().forEach {
            if (it.state.name == "NOT_UPLOADED" && it.retryCount!!.toInt() < 5) {
                if (it.deliverable?.success == true) {
                    it.state = RetentionUploadStatus.UPLOADED
                    println("RetentionUploadStatus->UPLOADED")
                } else {
                    val schemaService = SchemaServiceImpl()
                    val schemas = schemaService.initializeSchemas(definition, emptyMap())
                    val parameters = definition.parameterPolicy.policy(schemas.parametersSchema)
                    val delivery = deliveryPolicyService.policy<Deliverable>(ValidDeliveryPolicy.RETENTION_ONLY, schemas.deliverySchema)
                    val deliveryFunction = delivery.createDeliveryStep()
                    deliveryFunction(parameters, listOfDeliverables)
                    it.retryCount = it.retryCount!!.plus(1L)
                }
                retentionRepository.save(it)
            }
        }
    }

【问题讨论】:

标签: jpa kotlin spring-data-jpa mockito


【解决方案1】:

如果您有一个带有@Transactional 注释的方法saveOutput(),则需要在调用saveOutput() 的所有其他方法之上添加@Transactional,以便事务实际提交。

【讨论】:

    猜你喜欢
    • 2016-05-03
    • 1970-01-01
    • 2021-03-26
    • 1970-01-01
    • 1970-01-01
    • 2011-07-23
    • 1970-01-01
    • 1970-01-01
    • 2019-05-30
    相关资源
    最近更新 更多