Grails, GPars and data persistence

2019-04-21 00:02发布

问题:

Something is not getting flushed. A simplified example of what's happening:

def testDemo() {
    def person = new Person(...)
    person.save(flush: true)

    println "Number of people after save: " + Person.all.size()

    def dummyList = [1, 2, 3, 4, 5]

    GParsPool.withPool { num ->
        println "Number of people after withPool: " + Person.all.size()
        dummyList.eachParallel {
            println "Number of people after eachParallel " + Person.all.size()
            Person.withTransaction {
            ...

This outputs:

Number of people after save: 1
Number of people after withPool: 1
Number of people after eachParallel: 0

I don't understand if I have to do something with Session and Transaction to make the data persist or if this is a bug in GPars. What is going on here at the underlying hibernate level?

I want the recently created Person to be visible within the parallel closure.

回答1:

Gpars is a multi-threaded tool and the hibernate session injected in your domain class isn't thread-safe.

Try using these methods or invoking SessionFactory directly:

  • withNewSession
  • withNewTransaction

Beware that opening a session for each thread can be extremely costly and might flood your database with new connections.



回答2:

I recently have a similar problem. As I understood, it seems to be that the threads could not bind the hibernate session, I can't get it to work either. If you don't really need it, try to write code dealing with persistence out of GPars. That is the way I get it to work.