我試圖創建存儲庫方法,以便我可以顯示,而訪問本書的所有作者的詳細信息(反之亦然)。這是多對多關係,模型類是這樣的: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。
感謝您提前給予的幫助。
ID是沒有意義的,你是什麼讓圖書的作者呢?你需要退還一本書的作者? –
獲得書籍作者,因爲一本書可以有很多作者 –
檢查我的答案,你想返回一本書的作者集,而不是返回書籍列表 –