Grails (2.3.7) 中的并发问题似乎没有明确的解决方案。我已经尝试了所有建议,但是当我推送并发线程数时,以下代码总是失败:
package simpledb
import grails.transaction.Transactional
import groovy.transform.Synchronized
import org.apache.commons.logging.LogFactory
@Transactional
class OwnerService {
private static final myLock1 = new Object()
private static final myLock2 = new Object()
@Synchronized('myLock1')
static public saveOwner(def ownerName) {
def ownerInstance = null
Owner.withNewTransaction {
ownerInstance = Owner.findOrCreateByName(ownerName)
ownerInstance.save(failOnError: true, flush: true)
}
ownerInstance
}
@Synchronized('myLock2')
static public associateDog(def ownerId, def dogId) {
def lockedOwnerInstance
Owner.withNewTransaction {
lockedOwnerInstance = Owner.lock(ownerId)
def lockedDogInstance = Dog.lock(dogId)
lockedOwnerInstance.addToDogs(lockedDogInstance)
lockedOwnerInstance.save(failOnError: true, flush: true)
}
lockedOwnerInstance
}
}
它在“deflockedDogInstance = Dog.lock(dogId)”行上失败:
Error 500: Internal Server Error
URI
/simpledb/JsonSlurper/api
Class
org.hibernate.StaleObjectStateException
Message
Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect): [simpledb.Dog#111]
上面的设计非常简单,在 Owner 和 Dog 之间存在多对多关系:
狗类:
package simpledb
class Dog {
String name
Breed breed = null
Integer age = null
static hasMany = [owners: Owner]
static belongsTo = Owner
static mapping = { owners lazy: false }
static constraints = {
name blank: false, nullable: false, unique: true
breed nullable: true
age nullable: true
}
}
业主等级:
package simpledb
class Owner {
String name;
static hasMany = [dogs: Dog]
static mapping = { dogs lazy: false }
static constraints = {
}
}
仅供参考 - 数据库是 MySQL。
有什么建议吗?