如何更新grails域对象列表上的属性?

如何更新grails域对象列表上的属性?,grails,grails-2.0,grails-domain-class,Grails,Grails 2.0,Grails Domain Class,我有一个域类对象列表: def books = Books.findAllByTitleLike("%Hobbit%") 现在我想更新列表中所有书籍中可用的属性。通常,我会这样做 books.each { it.available = false; it.save() } 有更好的方法吗?我应该在一次交易中完成吗?比如: Book.withTransaction { ... } 您可以使用executeUpdate进行批量更新 def updatedRecords = Book

我有一个域类对象列表:

def books = Books.findAllByTitleLike("%Hobbit%")
现在我想更新列表中所有书籍中可用的属性。通常,我会这样做

books.each {
   it.available = false;
   it.save()
}
有更好的方法吗?我应该在一次交易中完成吗?比如:

Book.withTransaction { ... }

您可以使用executeUpdate进行批量更新

def updatedRecords = Book.executeUpdate("update Book set available = 'false' where title like'%Hobbit%' ")
根据评论: 它的hql和类似于sql

这是在内部查询中执行此操作的另一种方法:

def sql = """update Domain
set $fieldName = '$fieldValue'
where id in (select id from Domain1 where seqId = '$myid')"""
def updatedRecords = Domain.executeUpdate(sql)
或 在这方面:

"... where id in ('123','132','111')
我没有测试过这个,但你可能会说

def list= ['123','132','111']
" ... where id in ($list)"

您可以使用executeUpdate进行批量更新

def updatedRecords = Book.executeUpdate("update Book set available = 'false' where title like'%Hobbit%' ")
根据评论: 它的hql和类似于sql

这是在内部查询中执行此操作的另一种方法:

def sql = """update Domain
set $fieldName = '$fieldValue'
where id in (select id from Domain1 where seqId = '$myid')"""
def updatedRecords = Domain.executeUpdate(sql)
或 在这方面:

"... where id in ('123','132','111')
我没有测试过这个,但你可能会说

def list= ['123','132','111']
" ... where id in ($list)"

我更新了书单,因为我不想更新所有的布鲁克斯,但只更新了几本。那么,我如何将这个图书列表传递给您的查询呢?您可以将where子句添加到查询字符串中。比如x=1或x=2,类似这样的。您甚至可以使用inList,不确定inList是否适用,但您可以尝试一下。但一般来说,您可以灵活地构建自己的查询sql,比如。刚刚注意到您更新了问题,您也应该能够使用like。我对我的答案进行了更改,看看是否有效。假设您有一个ID列表,您应该如何查询?我更新了图书列表,因为我不想更新所有Brooks,但只更新少数。那么,我如何将这个图书列表传递给您的查询呢?您可以将where子句添加到查询字符串中。比如x=1或x=2,类似这样的。您甚至可以使用inList,不确定inList是否适用,但您可以尝试一下。但一般来说,您可以灵活地构建自己的查询sql,比如。刚刚注意到您更新了问题,您也应该能够使用like。我对我的答案做了一个更改,看看它是否有效。假设您有一个ID列表,您应该如何查询?