I'm writing a small Grails app, and I keep on getting StaleObjectStateException:s for about 1/10:th of the calls to "createfoo" when running the following rather simple code. Most probably I'm missing out on the best way to use GORM.
This is the code:
def viewfoo = {
session.user.refresh()
// ...
}
def createfoo = {
session.user.refresh()
var user = session.user
if (param["name"]) {
var newFoo = new Foo()
newFoo.name = param["name"]
if (newFoo.validate()) {
newFoo.save()
if (user.validate()) {
user.addToFoos(newFoo)
} else {
user.discard()
}
} else {
newFoo.discard()
}
}
}
My questions regarding GORM best practices:
Is the "if-validate()-then-save()-else-discard()" the correct way do to persist a new object in GORM?
Should I validate all objects that I'm about to save()? I.e. should I validate both the Foo-object and the User-object in the above code? Will validating the User-object implicitly check the status of the Foo-object?
What did I do to deserve the StaleObjectStateException? :-)
The GORM/Hibernate exception:
Caused by: Object of class [Foo] with identifier [15]: optimistic locking failed; nested exception is org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect): [Foo#15]