【问题标题】:Delete object of my domain in a hasMany relationship在 hasMany 关系中删除我的域的对象
【发布时间】:2017-07-23 14:19:43
【问题描述】:

我使用 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) REFERENCES PUBLIC.PROJECT_AUTHOR(ID) (1)"; SQL 声明:从 id=? 的 project_column 中删除和版本=? [23503-195]

我想删除作者而不删除书籍。

【问题讨论】:

  • 你已经模拟了一个作者有很多书,所以所有的书都绑定到作者。如果删除作者,书籍将属于?因为它在那个时候是损坏的数据,所以它是正确的
  • 如果我删除作者,书籍必须继续存在
  • 我没有使用belongto

标签: grails grails-orm grails-domain-class


【解决方案1】:

简而言之,你正在尝试做的事情并不是很好的做法:

您可以声明如下映射:

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 关系,则当您尝试删除嵌套关系时,这种行为就会生效,这并不是什么新东西

【讨论】:

  • 我没有使用belongto
【解决方案2】:

默认情况下,hasMany 关系将数据库列添加到关系的“多”端。这意味着您的每个Books 都有一个列来存储author。要改变这一点,您可以定义一个连接表。

static mapping = {
    books joinTable: [name: 'author_books',
                      key: 'author_id',
                      column: 'book_id']
}

这将创建一个表来存储关系,因此删除作者不需要触及个别书籍。

【讨论】:

    猜你喜欢
    • 2014-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多