【问题标题】:How can I update a property on a list of grails domain objects?如何更新 grails 域对象列表上的属性?
【发布时间】:2013-04-10 16:57:24
【问题描述】:

我有一个域类对象列表:

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

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

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

有没有更好的方法来做到这一点?我应该在一笔交易中完成吗?喜欢:

Book.withTransaction { ... }

【问题讨论】:

    标签: grails grails-2.0 grails-domain-class


    【解决方案1】:

    您可以使用 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列表,你应该如何查询?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-14
    • 2010-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多