在映射表中允许重复与多余列

时间:2018-03-27 09:37:09

标签: grails gorm

我有两个与额外列有多对多关系的域类。我通过遵循论坛中的逻辑在域类之下创建,但仍然面临将数据保存在其他域类中的问题.Roylaty是要保存的附加列映射表中的值。

以下是3个域类:

class AuthorBook implements Serializable {
    Author author
    Book book
    String royalty 
    boolean equals(other) {
        if (!(other instanceof AuthorBook)) {
            return false
        }
        other.author?.id == author?.id &&
        other.book?.id == book?.id
    }
    int hashCode() {
        def builder = new HashCodeBuilder()
        if (author) builder.append(author.id)
        if (book) builder.append(book.id)
        builder.toHashCode()
    }
    static AuthorBook get(long authorId, long bookId) {
        find 'from AuthorBook where author.id=:authorId and book.id=:bookId',
        [authorId: authorId, bookId: bookId]
    }
    static AuthorBook create(Author author, Book book, boolean flush = false) {
        new AuthorBook(author: author, book: book).save(flush: flush, insert: true)
    }
} 
class Author implements Serializable{
    string name(nullable:false,unique:true)
    Set<Book> getBooks() {
        AuthorBook.findAllByAuthor(this).collect { it.book } as Set
    }
}
class Book implements Serializable{
    string title(nullable:false,unique:true)
    Set<Author> getAuthors() {
        AuthorBook.findAllByBook(this).collect { it.author } as Set
    }
}

在我的一个控制器中,我编写了以下逻辑:

def author1 = new Author("ABC")
author.save(flush:true)
def book1= new Book("GORM")
book.save(flush:true)
def authorBook = new AuthorBook(royalty:100,author:author1,book:book1)
authorBook.save(flush:true)

对于作者和书籍,它按预期工作,即它不允许重复,也在映射表中。它不会允许重复,但我希望输出在映射表中如下所示

Author                      AuthorBook                        Book
id Name               id author_id book_id royalty            id title
1  XYZ                 1   1         1      500               1  Gorm
                       2   1         1      1000   

它不会保存此值,因为考虑到author_idbook_id的组合是唯一的,即使我没有在ID中设置任何复合键映射表。

我应该在映射表中更改哪些内容以允许重复?

1 个答案:

答案 0 :(得分:0)

您可以手动将该行插入数据库吗?我怀疑这是由equalshashcodeAuthorBook的实施引起的。

这两个对象是相同的: author=1;book=1;royalty=100author=1;book=1;royalty=500,因为您的平等方法只是比较作者和书籍。