在下面的代码中,我如何删除与作者相关的所有旧商店记录,然后插入一个新记录
域类
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
}
}
我假设您已经检索了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)
}
}
另一种选择是将这些方法添加到域类中,这可能是更可取的,尤其是如果您在应用程序中需要多个位置的情况下。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句