以author
,book
和加入表author_books
为例,加上royalty
列:
CREATE TABLE 'author_books' (
'author_id` bigint(20) NOT NULL,
'book_id' bigint(20) NOT NULL,
'royalty' int NOT NULL,
PRIMARY KEY ('author_id', 'book_id') ,
INDEX 'FK24C812F6183CFE1B' ('book_id'),
INDEX 'FK24C812F6DAE0A69B' ('author_id')
)
如果我没有db-reverse-engineer插件生成AuthorBooks类,生成的代码将是:
class Author {
String name
static hasMany = [books: Book]
}
class Book {
String title
static hasMany = [authors: Author]
static belongsTo = [Author]
}
以下代码:
def author1 = new Author(name: 'author1').addToBooks(new Book(title:
'book1')).save(flush: true)
会在author
表中插入一行,在book
表中插入一行,但由于author_books
不能为空而无法插入royalty
。
但是如果让db-reverse-engineer插件生成AuthorBooks类,生成的代码将是:
class Author {
String name
static hasMany = [authorBookses: AuthorBooks]
}
class Book {
String title
static hasMany = [authorBookses: AuthorBooks]
}
class AuthorBooks implements Serializable {
Long authorId
Long bookId
Integer royalty
Author author
Book book
int hashCode() {
def builder = new HashCodeBuilder()
builder.append authorId
builder.append bookId
builder.toHashCode()
}
boolean equals(other) {
if (other == null) return false
def builder = new EqualsBuilder()
builder.append authorId, other.authorId
builder.append bookId, other.bookId
builder.isEquals()
}
static belongsTo = [author: Author, book: Book]
static mapping = {
author insertable: false // these insertable and updateable codes were manually added
author updateable: false // otherwise it would not run
book insertable: false
book updateable: false
id composite: ["authorId", "bookId"]
version false
}
}
在这种情况下,我无法致电author.addToAuthorBooks(new AuthorBooks( ))
,因为author_books
无法author_id
或book_id
成为null
。最后,我需要执行以下操作才能使其正常工作:
def author1 = new Author(name: 'author1').save(flush: true)
def book1 = new Book(title: 'book1').save(flush: true)
def authorbook1 = new AuthorBooks(authorId: author1.id, bookId: book1.id,
royalty: 50, author: author1, book: book1).save(flush: true)
这是我可以接受的。但是,在作者和图书类中拥有hasMany关联有什么好处?有更好的方法吗?理想情况下,像下面这样的东西会很酷
def author1 = new Author(name: 'author1').addToBooks(book: new Book(title: 'book1'),
royalty: 50).save(flush: true)
答案 0 :(得分:1)
我想推荐一些更改,特别是在您的AuthorBooks域中:
custom user control
为书籍和作者提供额外的ID是多余的。我不是100%肯定我会建议的,但是值得尝试以下内容:
custom user control