映射表中允许与多余列进行多对多关系的重复项 [英] Duplicates to be allowed in the mapping table for many to many relationship with extra column
问题描述
我有两个与额外的列有很多关系的领域类.我按照论坛中的逻辑创建了下面的领域类,但在将数据保存到额外的领域类中时仍然遇到问题.Roylaty是要保存的额外的列映射表中的值.
I have two domain classes with many to many relationship with extra column.I created below domain classes by following the logic from the forums and still face an issue in saving the data in additional domain class.Roylaty is the additional column to save the value in the mapping table.
以下是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
}
}
在我的一个控制器中,我编写了以下逻辑:
In one of my controllers i wrote the below logic:
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)
对于作者和书籍,它都可以按预期工作,即不允许重复,并且在映射表中也不允许.它不允许重复,但我希望输出在映射表中如下所示
For both author and book, it works as expected i.e it won't allow duplicates and in the mapping table too. it won't allow duplicates but I want the output to be as below in the mapping table
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
即使我未在映射表中的id上设置任何复合键,它也不会保存该值,因为它认为author_id
和book_id
的组合是唯一的.
It won't save this value as it is considering the combination of author_id
and book_id
to be unique even though I did not set any composite key on id's in the mapping table.
我应该在映射表中进行哪些更改以允许重复?
What should I change in the mapping table to allow duplicates?
推荐答案
您可以手动将该行插入数据库吗?我怀疑这是由于您在AuthorBook
上实施了equals
和hashcode
而引起的.
Can you manually insert that row into the database? I suspect this is caused by your implementation of equals
and hashcode
on AuthorBook
.
这两个对象是相同的:
author=1;book=1;royalty=100
和author=1;book=1;royalty=500
,因为您的相等方法仅比较作者和书籍.
These two objects are the same:
author=1;book=1;royalty=100
and author=1;book=1;royalty=500
because your equality methods are only comparing author and book.
这篇关于映射表中允许与多余列进行多对多关系的重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!