代码之家  ›  专栏  ›  技术社区  ›  Michael asterite

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

  •  2
  • Michael asterite  · 技术社区  · 12 年前

    我有一个域类对象列表:

    def books = Books.findAllByTitleLike("%Hobbit%")
    

    现在,我想更新此列表中所有书籍中的“可用”属性。通常情况下,我会这样做

    books.each {
       it.available = false;
       it.save()
    }
    

    有更好的方法吗?我应该在一笔交易中完成吗?喜欢:

    Book.withTransaction { ... }
    
    1 回复  |  直到 12 年前
        1
  •  4
  •   Alidad    12 年前

    您可以使用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)"