Grails groovy删除旧记录

时间:2013-10-10 09:57:44

标签: java grails groovy gson domaincontroller

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

域类

 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
    }
}

1 个答案:

答案 0 :(得分: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)
    }
}

另一种方法是在域类中添加这些方法,这可能更合适,特别是如果您在应用程序中需要多个位置。