2

This is a conceptional example, but I do not understand how to implement this.

I have tables as follows:

BOOK
------------
BOOK_ID

BOOK_AUTHOR
------------
BOOK_ID
AUTHOR_ID

AUTHOR
------------
AUTHOR_ID

Which map to the following hibernate many to many relationship:

Book

@Entity
public class Book implements Serializable {
@ManyToMany(
    targetEntity=org.hibernate.test.metadata.manytomany.Author.class,
    cascade={CascadeType.PERSIST, CascadeType.MERGE}
)
@JoinTable(
    name="BOOK_AUTHOR",
    joinColumns=@JoinColumn(name="BOOK_ID"),
    inverseJoinColumns=@JoinColumn(name="AUTHOR_ID")
)
public Collection getAuthors() {
    return authors;
}

}               

Author

@Entity
public class Author implements Serializable {
@ManyToMany(
    cascade = {CascadeType.PERSIST, CascadeType.MERGE},
    mappedBy = "authors",
    targetEntity = Book.class
)
public Collection getBooks() {
    return books;
}

}

However, I live in a world where, a book and an author must have matching publishers but a book can exist without an author and an author can exist without a book. So, to my tables I have added a publisher id:

BOOK
------------
BOOK_ID
PUBLISHER_ID

BOOK_AUTHOR
------------
BOOK_ID
AUTHOR_ID
PUBLISHER_ID

AUTHOR
------------
AUTHOR_ID
PUBLISHER_ID

This in the database layer, would mean that the publisher id must match across all three tables meaning a book and author must have the same publisher, but how do I implement this using hibernate mapping?

mogronalol
  • 2,946
  • 8
  • 38
  • 56
  • So Book and Author both have a Publisher field that is optional. But why do you need to add PUBLISHER_ID in the join table? – oksayt Aug 17 '11 at 15:37
  • because the book and author must have the same publisher in order to relate to each other in the BOOK_AUTHOR table, enforced by a composite key – mogronalol Aug 17 '11 at 17:28

0 Answers0