tailieunhanh - Beginning Hibernate From Novice to Professional phần 5

Khi một liên kết nhiều-nhiều không liên quan đến một thực thể lớp học đầu tiên tham gia vào hai bên của mối quan hệ, một bảng liên kết phải được sử dụng để duy trì mối quan hệ. Điều này có thể được tạo ra tự động, hoặc các chi tiết có thể được thành lập theo cách tương tự như với các bảng liên kết được mô tả trong | CHAPTER 6 MAPPING WITH ANNOTATIONS 119 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 generated 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 ofthe Many-to-Many Association @ManyToMany cascade ALL public Set Author getAuthors return authors The Author entity is managed .