我试图创建存储库方法,以便我可以在访问本书所有作者的详细信息时显示(反之亦然)。它的多对多关系,模型类看起来像这样:
作者(模特)课程:
@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 :(得分:2)
您需要在一侧(拥有实体端)指定连接表,并在另一侧指定mappedBy,例如在Book实体中
@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