简体   繁体   中英

withTransaction and saving a lot of objects?

In the controller method is the following chunk of code.

def stat = ''

    stat = assignBibNumbers(compositeEvent.id)

Here is the private function called in the above code: Please note that only the relevant part is shown

private def assignBibNumbers(Long id){

    ...

    def eventRange = bibsService.convertRangeStringToRangeList(compositeEvent.bibsRange)


    for(int j=0; j<finRegsList.size(); j++){

        finRegsList[j].raceParticipant.bibNumber = eventRange[j]
        finRegsList[j].save()


    }


        return "Bib Setup Complete! No bib assignment was made."




}

The save doesnt work in the above case. THe bib numbers are not assigned.

Now if i change the above first part of the code to

def stat = ''
RaceRegistration.withTransaction { status ->
    stat = assignBibNumbers(compositeEvent.id)
}

it works! So i am very confused why i should wrap the function in a withTransaction block. I thought even without wrapping in in transaction block the save should still work. What is causing the save() to not work without a transaction block? Should saves in a loop always be wrapped in a transaction block? I appreciate any help! Thanks!

I thought even without wrapping in in transaction block the save should still work.

This is true if your method is annotated with @Transactional , or the class. In your case, try annotating assignBibNumbers() , like so

@Transactional
private def assignBibNumbers(Long id){...}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM