假设我有以下域类:
@Entity
class TestDomain {
public static final ID_PREFIX = "prefix-"
String uniqueId
constriaints = {
uniqueId nullable: true
}
}默认情况下,grails域类也有一个id属性。接下来,我想以这样的方式设置uniqueId:当我创建一个新的TestDomain对象时,uniqueId属性包含类似于第一个创建的对象的prefix-1,第二个对象的prefix-2,依此类推。
我的方法是认识到在TestDomainController的save操作中
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),事情也不会改变。
另一种方法是将所有的第一次保存、修改和第二次保存都放入testDomainService的save方法中,但没有成功-同样的错误也发生了。
在同一事务中,保存域对象、更改域对象并再次保存域对象通常是不可能的吗?
发布于 2014-10-30 17:52:17
@Entity
class TestDomain {
public static final ID_PREFIX = "prefix-"
String uniqueId
constriaints = {
uniqueId nullable: true
}
def afterInsert() {
uniqueId = ID_PREFIX + id
}
}https://stackoverflow.com/questions/25786936
复制相似问题