Grails 删除hasMany关系中我的域的对象
我使用Grails构建以下域:Grails 删除hasMany关系中我的域的对象,grails,gorm,grails-domain-class,Grails,Gorm,Grails Domain Class,我使用Grails构建以下域: class Book { String title } class Author { String name static hasMany = [books: Book] } def book1 = new Book(title: "The Shining") def author1 = new Author(name: "Stephen King") author1.addToBooks(book1) 如果尝试删除author
class Book {
String title
}
class Author {
String name
static hasMany = [books: Book]
}
def book1 = new Book(title: "The Shining")
def author1 = new Author(name: "Stephen King")
author1.addToBooks(book1)
如果尝试删除author1
:
author1.books.clear()
author1.delete flush:true
我得到这个错误:
信息
空因
引用完整性约束冲突:“FKQG8TLCGMC6WKG6ILECFOXSLVS:PUBLIC.PROJECT\u BOOK FOREIGN
密钥(图书作者ID)引用公共。项目作者(ID)(1)”;SQL
语句:从id=?的project_列中删除?和版本=?
[23503-195]
我想删除一位作者而不删除书籍。简言之,练习你想做的事情并不是很好: 您可以声明如下映射:
static mapping={
// This is how you tell hibernate to remove all records so you will need the reverse of this
//books cascade:'all-delete-orphan'
//possible this - you will need to experiment
books cascade: 'none'
}
但也许你应该以完全不同的方式申报
class Book {
String title
Long autorId
Author getAuthor() {
return Authoer.get(authorId)
}
}
class Author {
String name
List<Books> getBooks() {
return Books.findAllByAuthorId(this.id)
}
}
这可能使其与以下方面的关系更加松散:
static belongsTo = Author
通常情况下,如果您有这种hasMany关系,那么当您尝试删除嵌套关系时,这种行为会起作用,它不是什么新的东西简言之,您尝试做的并不是很好的实践: 您可以声明如下映射:
static mapping={
// This is how you tell hibernate to remove all records so you will need the reverse of this
//books cascade:'all-delete-orphan'
//possible this - you will need to experiment
books cascade: 'none'
}
但也许你应该以完全不同的方式申报
class Book {
String title
Long autorId
Author getAuthor() {
return Authoer.get(authorId)
}
}
class Author {
String name
List<Books> getBooks() {
return Books.findAllByAuthorId(this.id)
}
}
这可能使其与以下方面的关系更加松散:
static belongsTo = Author
通常情况下,如果您有此hasMany关系,则当您尝试删除嵌套关系时,这种行为会起作用。默认情况下,
hasMany
关系会在关系的“多”端添加一个数据库列。这意味着您的每本书籍
都有一列存储作者
。若要更改,可以改为定义联接表
static mapping = {
books joinTable: [name: 'author_books',
key: 'author_id',
column: 'book_id']
}
这将创建一个表来存储关系,因此删除作者不需要接触单个书籍。默认情况下,
hasMany
关系会在关系的“many”端添加一个数据库列。这意味着您的每本书籍
都有一列存储作者
。若要更改,可以改为定义联接表
static mapping = {
books joinTable: [name: 'author_books',
key: 'author_id',
column: 'book_id']
}
这将创建一个表来存储关系,因此删除作者将不需要触及单个书籍。您已建模一个作者有许多书籍,因此所有书籍都绑定到作者。如果你删除了作者,这些书将属于谁?因为在这一点上,它是破碎的数据,因此它是正确的,如果我删除作者,这些书必须继续存在。我没有使用belong to这个问题,因为你已经建模了一个作者有许多书,因此所有的书都与作者绑定。如果你删除了作者,这些书将属于谁?因为在这一点上,它是被破坏的数据,所以如果我删除作者,它是正确的,这些书必须继续存在。我没有使用belongto和这个问题相同。我没有使用belongto。我没有使用belongto