Java Reference
In-Depth Information
Listing 6-18 shows a fairly typical application of the @JoinTable annotation to specify the
name of the join table and its foreign keys into the associated entities.
Listing 6-18. A Unidirectional One-to-Many Association with a More Fully Specified Join Table
@OneToMany(cascade = ALL)
@JoinTable(
name="PublishedBooks",
joinColumns = { @JoinColumn( name = "publisher_id") },
inverseJoinColumns = @JoinColumn( name = "book_id")
)
public Set<Book> getBooks() {
return books;
}
Mapping a Many-to-Many Association
When a many-to-many association does not involve a first-class entity joining the two sides
of the relationship, a link table must be used to maintain the relationship. This can be gen-
erated automatically, or the details can be established in much the same way as with the
link table described in the “Mapping a Many-to-One or One-to-Many Association” section
of the chapter.
The appropriate annotation is naturally @ManyToMany , and takes the following attributes:
mappedBy is the field that owns the relationship—this is only required if the association is
bidirectional. If an entity provides this attribute, then the other end of the association is
the owner of the association, and the attribute must name a field or property of that entity.
targetEntity is the entity class that is the target of the association. Again, this may be
inferred from the generic or array declaration, and only needs to be specified if this is not
possible.
cascade indicates the cascade behavior of the association, which defaults to none.
fetch indicates the fetch behavior of the association, which defaults to LAZY .
The example maintains a many-to-many association between the Book class and the
Author class. The Book entity owns the association, so its getAuthors() method must be
marked with an appropriate @ManyToMany attribute, as shown in Listing 6-19.
Listing 6-19. The Book Side of the Many-to-Many Association
@ManyToMany(cascade = ALL)
public Set<Author> getAuthors() {
return authors;
}
The Author entity is managed by the Topic entity. The link table is not explicitly managed,
so, as shown in Listing 6-20, we mark it with a @ManyToMany annotation and indicate that the
foreign key is managed by the authors attribute of the associated Topic entity.
Search WWH ::




Custom Search