JonB
JonB

Reputation: 814

Correctly commit to database using @Transactional in spring-data

I have a test function, that should perform the following task

  1. insert data to db
  2. query db and verify data is as expected

The problem is that in my test, the data has not been committed to the db, like it's stuck in some transactional step, how can I surely commit the data before the second query is executed.

This is a part of my test function, @Rollback(false) is just for development phase.

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

saveOutput func. sample code

@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 func code

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)
            }
        }
    }

Upvotes: 0

Views: 352

Answers (1)

mckszcz
mckszcz

Reputation: 144

If you have a method saveOutput() with @Transactional annotation, you need to add @Transactional above every other method that is calling saveOutput() for the transaction to actually commit.

Upvotes: 1

Related Questions