0

在以下代码中,如何删除与作者相关的所有旧商店记录并插入新的

领域类

 class Store {
Date dateCreated
Date lastUpdated

static belongsTo = [author: Author]
    static constraints = {
     }
  }

域控制器

 def update() {
    if (!requestIsJson()) {
        respondNotAcceptable()
        return
    }

    def bookInstance = book.get(params.id)
    if (!bookInstance) {
        respondNotFound params.id
        return
    }

    if (params.version != null) {
        if (bookInstance.version > params.long('version')) {
            respondConflict(bookInstance)
            return
        }
    }

    def stores = bookInstance.stores

    //bookInstance.delete(flush:true);
    //stores.delete(flush:true);



    bookInstance.properties = request.GSON

    if (bookInstance.save(flush: true)) {
        respondUpdated bookInstance

    } else {
        respondUnprocessableEntity bookInstance
    }
}
4

1 回答 1

0

我假设您已检索到Author要修改的实例。在这种情况下,您可以简单地遍历与作者关联的商店并一一删除。是否要在每次删除后刷新或等到所有内容都被删除取决于您。

假设你有一个Author看起来像这样的类:

class Author {
    static hasMany = [stores: Store]
}

然后您可以向控制器添加方法:

class MyController {
    SessionFactory sessionFactory

    def deleteStoresFromAuthor(Author author) {
        author.stores.each { it.delete(flush: true) }
    }

    def deleteStoresFromAuthorWithDelayedFlush(Author author) {
        author.stores.each { it.delete() }
        sessionFactory.currentSession.flush()
    }

    def createStoreForAuthor(Author author) {
        new Store(author: author, dateCreated: new Date(), lastUpdated: new Date()).
                save(flush: true)
    }
}

另一种选择是在域类中添加这些方法,这可能更可取,特别是如果您在应用程序中需要它们的地方不止一个。

于 2013-10-10T12:13:15.623 回答