2017-08-09 55 views
0

我試圖創建存儲庫方法,以便我可以顯示,而訪問本書的所有作者的詳細信息(反之亦然)。這是多對多關係,模型類是這樣的:HQL多對多的存儲庫方法

作者(模型)類:

@Entity 
@Table(name = "author") 
public class Author { 

    @Id 
    @GeneratedValue(strategy = GenerationType.AUTO) 
    @Column(name = "author_id") 
    private int authorId; 
    @Column(name = "name") 
    private String name; 
    @Column(name = "surname") 
    private String surname; 
    @Column(name = "date_of_birth") 
    private Date dateOfBirth; 

    @Column(name = "alive") 
    private boolean alive; 

    @ManyToMany(cascade = CascadeType.ALL, mappedBy="authors") 
    @JoinTable(name = "book_author", 
      joinColumns = @JoinColumn(name = "book_id"), 
      inverseJoinColumns = @JoinColumn(name = "author_id")) 
    private Set<Book> books = new HashSet<Book>(); 

書(模型)類

@Entity 
@Table(name = "book") 
public class Book { 

    @Id 
    @GeneratedValue(strategy = GenerationType.AUTO) 
    @Column(name = "book_id") 
    private int bookId; 
    @Column(name = "isbn") 
    private long isbn; 
    @Column(name = "title") 
    private String title; 
    @Column(name = "title_original") 
    private String titleOriginal; 
    @Column(name = "premiere_date") 
    private Date premiereDate; 
    @ManyToMany(cascade = CascadeType.ALL, mappedBy="books") 
    @JoinTable(name = "book_author", joinColumns = { @JoinColumn(name = "book_id") }, inverseJoinColumns = { @JoinColumn(name = "author_id") }) 
    private Set<Author> authors = new HashSet<Author>(0); 

BookRepository等級:

@Repository 
public interface BookRepository extends CrudRepository<Book, Integer> { 

    List<Book> findByIsbn(@Param("isbn") long isbn); 
    List<Book> findByTitle(@Param("title") String title); 
    List<Book> findByTitleOriginal(@Param("titleOriginal") String titleOriginal); 
    @Query("SELECT b FROM Book b WHERE b.premiereDate BETWEEN :startYear AND :endYear ORDER BY b.premiereDate") 
    public List<Book> getBooksBetweenDate(@Param("startYear")int startYear, @Param("endYear")int endYear); 




@Query("SELECT b FROM Book b JOIN b.authors a WHERE a.authorId =:idAuthor") 
public List<Book> getBookAuthors(???) 

我認爲我的模型類和hql查詢存儲庫中都可以,但我不知道如何創建方法getBookAuthors

感謝您提前給予的幫助。

+0

ID是沒有意義的,你是什麼讓圖書的作者呢?你需要退還一本書的作者? –

+0

獲得書籍作者,因爲一本書可以有很多作者 –

+0

檢查我的答案,你想返回一本書的作者集,而不是返回書籍列表 –

回答

2

你需要在一次側(其所屬的實體側)和的mappedBy在另一邊,所以forexample在自己的圖書實體

@ManyToMany(cascade = CascadeType.ALL. mappedBy="books") 
    private Set<Author> authors = new HashSet<Author>(0); 

所以,現在你有書之間的雙向關係到指定連接表作者,如果您要檢索的作者一本書你需要的是使用資源庫檢索圖書,然後獲取其作者

Book book = BookRepository.findOne(bookId);//bookId contains the id of your book 
Set<Author> authors = book.getAuthors();//im supposing you have getter for your authers in Book class 
+0

後添加,如何使我的方法getBookAuthors工作? –

+0

另外,編輯原文 –

+0

@TylerDurden我編輯了答案,是你需要的嗎? –