Reputation: 33297
I have a list of domain class objects:
def books = Books.findAllByTitleLike("%Hobbit%")
Now I want to update the property "available" in all books in this list. Normally, I would do
books.each {
it.available = false;
it.save()
}
Is there a better way to do that? Should I do it in one transaction? Like:
Book.withTransaction { ... }
Upvotes: 2
Views: 3217
Reputation: 5538
You can use bulk update using executeUpdate
def updatedRecords = Book.executeUpdate("update Book set available = 'false' where title like'%Hobbit%' ")
Per comments: Its hql and its similar to sql.
This is another way you can do it (inner query):
def sql = """update Domain
set $fieldName = '$fieldValue'
where id in (select id from Domain1 where seqId = '$myid')"""
def updatedRecords = Domain.executeUpdate(sql)
Or Something in this line:
"... where id in ('123','132','111')
I have not tested this but you might be able to say
def list= ['123','132','111']
" ... where id in ($list)"
Upvotes: 4