【问题标题】:Grails (StaleObjectStateException) - set domain object's property dependent on its ID after savingGrails (StaleObjectStateException) - 保存后根据其 ID 设置域对象的属性
【发布时间】:2014-09-11 12:00:54
【问题描述】:

假设我有以下域类:

@Entity
class TestDomain {

    public static final ID_PREFIX = "prefix-"

    String uniqueId

    constriaints = {
        uniqueId nullable: true
    }
}

grails 默认域类也有一个id 属性。在此之后,我想以这样的方式设置uniqueId,当我创建一个新的TestDomain 对象时,uniqueId 属性包含类似于prefix-1 的第一个创建的对象,prefix-2 的第二个,等等开。

我的方法是在TestDomainControllersave 操作中实现这一点:

def save(TestDomain testDomainInstance) {
    if (testDomainInstance == null) {
        notFound()
        return
    }

    if (testDomainInstance.hasErrors()) {
        respond testDomainInstance.errors, view:'create'
        return
    }

    testDomainService.save(testDomainInstance) //.save flush:true
    testDomainInstance.uniqueId = TestDomain.ID_PREFIX + testDomainInstance.id
    testDomainService.save(testDomainInstance) //.save flush:true

    request.withFormat {
        form multipartForm {
            flash.message = message(code: 'default.created.message', args: [message(code: 'TestDomain.label', default: 'Test Domain'), testDomainInstance.id])
            redirect testDomainInstance
        }
        '*' { respond testDomainInstance, [status: CREATED] }
    }
}

但是,一旦我保存对象,我就会收到以下错误:

StaleObjectStateException occurred when processing request: ...
Message
Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect) : [test.TestDomain#1]

现在,我该怎么做才能让它运行起来?或者,有没有可能以更漂亮的方式设置uniqueId 的值?目前,我有点卡住了。

感谢您的帮助!

编辑:

我现在尝试在第一个save 之后将redirect 设置为另一个操作,以便在那里设置uniqueId。但是,我得到同样的错误。即使我在testDomainService 中使用save(flush: true),问题也不会改变。

另一种方法是将所有第一次保存、更改和第二次保存放入testDomainServicesave 方法但没有成功 - 发生了同样的错误。该服务是事务性的。

通常不可能保存域对象、更改它并在同一个事务中再次保存吗?

【问题讨论】:

    标签: grails properties controller grails-domain-class


    【解决方案1】:
    @Entity
    class TestDomain {
        public static final ID_PREFIX = "prefix-"
        String uniqueId
         constriaints = {
            uniqueId nullable: true
        }
      def afterInsert() {
         uniqueId = ID_PREFIX + id
       }
    }
    

    【讨论】:

    • 我试过了,但我得到了同样的错误(StaleObjectStateException)......它在你的应用程序中有效吗?
    • org.hibernate.StaleObjectStateException 如果两个线程同时修改同一个对象,请阅读此内容。oodlestechnologies.com/blogs/…
    猜你喜欢
    • 1970-01-01
    • 2011-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多