首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Grails (StaleObjectStateException) -保存后根据ID设置域对象的属性

Grails (StaleObjectStateException) -保存后根据ID设置域对象的属性
EN

Stack Overflow用户
提问于 2014-09-11 20:00:54
回答 1查看 207关注 0票数 0

假设我有以下域类:

代码语言:javascript
复制
@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操作中

代码语言:javascript
复制
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] }
    }
}

然而,一旦我保存了对象,我就会得到以下错误:

代码语言:javascript
复制
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方法中,但没有成功-同样的错误也发生了。

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

EN

回答 1

Stack Overflow用户

发布于 2014-10-30 17:52:17

代码语言:javascript
复制
@Entity
class TestDomain {
    public static final ID_PREFIX = "prefix-"
    String uniqueId
     constriaints = {
        uniqueId nullable: true
    }
  def afterInsert() {
     uniqueId = ID_PREFIX + id
   }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25786936

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档