开发者

removeFrom with cascade all-delete-orphan does not work

Grails 1.3.7 with MySQL 5.5

Either I must be doing something brain-dead, or this is related to Grails issues http://jira.grails.org/browse/GRAILS-5804 and http://jira.grails.org/browse/GRAILS-4121 and similar. I have:

class Author {
    String name
    static hasMany = [books: Book]
    static constraints = {
        books cascade: 'all-delete-orphan'
    }
    String toString() 开发者_StackOverflow社区{
        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!")
        }
    }

But when I navigate to localhost:8080/foo/author/index I get a 'not-null property references a null or transient value: foo.Book.author' during the save()

I don't really know GORM-internals or Hibernate (proxied vs unproxied instances), I tried all combinations of using 'get' instead of 'find' but can't get this to work. Can someone explain how this is supposed to work?


I think you misplace the constraint, it should be like this:

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

NOT

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

That causes the problem. More information about this GORM gotchas can be found here(Deleting children).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜