removeCrom with cascade all-delete-orphan不起作用

时间:2011-04-17 05:42:25

标签: hibernate grails gorm

Grails 1.3.7 with MySQL 5.5

要么我必须做一些脑死亡的事情,要么这与Grails问题http://jira.grails.org/browse/GRAILS-5804http://jira.grails.org/browse/GRAILS-4121相似。 我有:

class Author {
    String name
    static hasMany = [books: Book]
    static constraints = {
        books cascade: 'all-delete-orphan'
    }
    String toString() {
        return name
    }
}

class Book {
    String title
    static belongsTo = [author: Author]
    static constraints = {
    }
    String toString() {
        return title
    }
}

Bootstrap:
def a = new Author(name: 'Author0')
a.save(flush: true, failOnError: true)      
def b = new Book(title: 'Book0')
a.addToBooks(b).save(flush: true, failOnError: true)

class AuthorController {
    def index = {
        println("Controller code: " + "Old books by author: " + Author.get(1).books)
        def author = Author.findByName("Author0")
        def oldBooks = []
        oldBooks += author.books  // to avoid ConcurrentModificationException
        oldBooks.each {
            author.removeFromBooks(it)
        }
        author.save(flush: true, failOnError: true)
        println("Controller code: " + "New books by author: " + Author.get(1).books)
            render("All done!")
        }
    }

但是当我导航到localhost:8080 / foo / author / index时,我得到一个'not-null属性引用null或transient值:foo.Book.author'在save()期间

我真的不知道GORM-internals或Hibernate(代理vs unproxied实例),我尝试了使用'get'而不是'find'的所有组合,但无法使其工作。有人可以解释一下这应该如何起作用吗?

1 个答案:

答案 0 :(得分:2)

我认为你错放了约束,它应该是这样的:

static mapping = {
    books cascade: "all-delete-orphan"
}

不是

static constraints = {
    books cascade: 'all-delete-orphan'
}

导致问题。有关此GORM陷阱的更多信息,请访问here(删除儿童)。