Spring JPARepository查询多对多交叉表
我有3个实体类,如下所示(示例取自) 图书类Spring JPARepository查询多对多交叉表,spring,hibernate,spring-data-jpa,Spring,Hibernate,Spring Data Jpa,我有3个实体类,如下所示(示例取自) 图书类 @Entity public class Book{ private int id; private String name; private Set<BookPublisher> bookPublishers; public Book() { } public Book(String name) { this.name = name; bookPubli
@Entity
public class Book{
private int id;
private String name;
private Set<BookPublisher> bookPublishers;
public Book() {
}
public Book(String name) {
this.name = name;
bookPublishers = new HashSet<>();
}
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@OneToMany(mappedBy = "book", cascade = CascadeType.ALL, orphanRemoval = true)
public Set<BookPublisher> getBookPublishers() {
return bookPublishers;
}
public void setBookPublishers(Set<BookPublisher> bookPublishers) {
this.bookPublishers = bookPublishers;
}
}
@Entity
public class Publisher {
private int id;
private String name;
private Set<BookPublisher> bookPublishers;
public Publisher(){
}
public Publisher(String name){
this.name = name;
}
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@OneToMany(mappedBy = "publisher")
public Set<BookPublisher> getBookPublishers() {
return bookPublishers;
}
public void setBookPublishers(Set<BookPublisher> bookPublishers) {
this.bookPublishers = bookPublishers;
}
}
我想问两件事
请告诉我是否可以使用JPA存储库查询多对多关系,如果可以,我是否可以直接查询,或者是否需要对实体类进行任何更改,我不确定您是否可以仅通过方法名进行查询。但您肯定可以使用JPA查询。类似这样的内容:
“从Book b中选择b JOIN b.bookpublisher bp JOIN bp.publisher p,其中p.id=?1”
。在BookRepository
获取出版商的书籍
findBooksByBookPublishersPublisherId(长publisherId)
获取未由出版商出版的书籍
findBooksByBookPublishersPublisherIdNot(长publisherId)
IMHO
Publication
比BookPublisher
更合适,因为Publisher
本身可能是BookPublisher
(出版书籍的出版社)您可以使用命名查询来满足您的要求:
@Query("select b from Book b where b.publisher.idd = ?1")
Book findByPublisherId(int id);
@Query("select b from Book b where b.publisher.idd <> ?1")
Book findByDifferentPublisherId(int id);
@Query(“从书b中选择b,其中b.publisher.idd=?1”)
Book findByPublisherId(内部id);
@查询(“从书b中选择b,其中b.publisher.idd?1”)
通过不同的发布者id(int id)查找图书;
查看更多详细信息。非常好。这就是我要找的。只是对JPA方法的命名约定感到困惑。谢谢
@Query("select b from Book b where b.publisher.idd = ?1")
Book findByPublisherId(int id);
@Query("select b from Book b where b.publisher.idd <> ?1")
Book findByDifferentPublisherId(int id);