使用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)
如果尝试删除author1
:
author1.books.clear()
author1.delete flush:true
我收到此错误:
信息 null引起的 参照完整性约束违规:“FKQG8TLCGMC6WKG6ILECFOXSLVS:PUBLIC.PROJECT_BOOK FOREIGN KEY(BOOK_AUTHOR_ID)参考PUBLIC.PROJECT_AUTHOR(ID)(1)“; SQL 声明:从project_column中删除id =?和版本=? [23503-195]
我想在不删除图书的情况下删除作者。
答案 0 :(得分:0)
简而言之,您尝试做的事情并不是很好:
您可以声明如下的映射:
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)
}
}
这样,除了你自己的id映射之外,书籍或作者之间没有真正的关系,所以不要做你创建的所有addToBooks
作者创建书籍而你设置book.authoriId=author.id
当您向前走过课程时,其余部分会通过您的查询动态查找。
缺点是它不是直接关系所以HQL查询等变得有点复杂
您还没有建议声明:
static belongsTo = [author:Author]
这可能会使它与以下内容更加松散:
static belongsTo = Author
通常情况下,如果你有这个hasMany关系,当你试图删除嵌套关系时,这种行为就会起作用,这不是什么新事物
答案 1 :(得分:0)
默认情况下,hasMany
关系会将数据库列添加到关系的“多个”端。这意味着您的每个Books
都有一列用于存储author
。要更改它,您可以改为定义连接表。
static mapping = {
books joinTable: [name: 'author_books',
key: 'author_id',
column: 'book_id']
}
这将创建一个用于存储关系的表格,因此删除作者无需触及单个书籍。