Grails,GPars和数据持久性

Ali*_*son 10 grails hibernate gpars

有些东西没有被冲洗.发生了什么的简化示例:

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 {
            ...
Run Code Online (Sandbox Code Playgroud)

这输出:

Number of people after save: 1
Number of people after withPool: 1
Number of people after eachParallel: 0
Run Code Online (Sandbox Code Playgroud)

我不明白我是否必须使用Session和Transaction来使数据保持不变或者这是GPars中的错误.底层的hibernate级别发生了什么?

我希望最近创建的Person在并行闭包中可见.

Rap*_*ael 12

Gpars是一个多线程工具,在您的域类中注入的hibernate会话不是线程安全的.

尝试使用这些方法或直接调用SessionFactory:

  • withNewSession
  • withNewTransaction

请注意,为每个线程打开会话可能会非常昂贵,并且可能会使用新连接充斥您的数据库.

  • +1"会话......不是线程安全的"谢谢!这就解释了为什么我需要在一个应该安全并发的地方锁定.我使用withNewSession而不是withTransaction. (2认同)