执行此操作的更多 Grails 方法是使用批处理。试试下面给出的例子:
编辑:改进的答案。现在,使用基于分页的批处理。
def noOfObjectsTobeProcessedAtAtime=1000//Step or pagination size...
List offsetMaxMapList = (0..User.count()-1).step(noOfObjectsTobeProcessedAtAtime).collect{[max:noOfObjectsTobeProcessedAtAtime,offset:it]}
offsetMaxMapList.each{offsetMaxMap->
addPermissionToUserInBatch(params)
}
def addPermissionToUserInBatch(params){
def batch = []
def session
def users = Users.createCriteria().list(params){}
users.eachWithIndex { user, index ->
batch << user
if (batch.size() >= batchSize) {
User.withTransaction {
batch.each {User userObject ->
addPermission(book, userObject, READ)
}
}
batch.clear()
} else if (batch.size() < batchSize && (users.size() - index - 1) == 0) {
User.withTransaction {
batch.each {User userObject ->
addPermission(book, userObject, READ)
}
}
batch.clear()
}
session = sessionFactory.getCurrentSession()
session.clear()
}
}
希望有帮助!!!