[英]Spring Data JPA: query ManyToMany, select by count
I have 2 entities: Book and Author. 我有2个实体:书籍和作者。 Each mapped to appropriate table. 每个映射到适当的表。 Also I have third table book_author
because these two entities have relation many-to-many. 我还有第三张表book_author
因为这两个实体具有多对多关系。 I need to select from DB all the books in which the number of authors is equal to count
. 我需要从数据库中选择作者人数等于count
所有书籍。
Book: 书:
@Entity(name = "Book")
@Table(name = "book")
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int idbook;
@NotNull
@Size(max = 100)
private String bookName;
private int bookYearWriting;
@ManyToMany(fetch = FetchType.LAZY,
cascade = {
CascadeType.PERSIST,
CascadeType.MERGE
})
@JoinTable(name = "author_book",
joinColumns = { @JoinColumn(name = "book_id") },
inverseJoinColumns = { @JoinColumn(name = "author_id") }
)
private List<Author> authors = new ArrayList<>();
...
}
Author: 作者:
@Entity(name = "Author")
@Table(name = "author")
public class Author {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int idauthor;
@NotNull
@Size(max = 100)
private String authorName;
@ManyToMany(fetch = FetchType.LAZY,
cascade = {
CascadeType.PERSIST,
CascadeType.MERGE
},
mappedBy = "authors")
private List<Book> books = new ArrayList<>();
...
}
And I want to get something like that: 我想要得到这样的东西:
@Repository
public interface BookRepository extends PagingAndSortingRepository<Book, Integer> {
List<Book> findAllByAuthorsCountIs(int count, Pageable pageable);
}
Please tell me how I can get this. 请告诉我我怎么能得到这个。
you can use collection size in Hql query. 您可以在Hql查询中使用集合大小。
For example ... 例如 ...
from Book book left join book.authors where book.authors.size == 3 从Book book左加入book.authors,其中book.authors.size == 3
For more information please refer below link... 有关更多信息,请参见下面的链接...
https://docs.jboss.org/hibernate/core/3.3/reference/en/html/queryhql.html https://docs.jboss.org/hibernate/core/3.3/reference/en/html/queryhql.html
@Query("select book from Book book left join book.authors where book.authors.size == ?1") List findAllByAuthorsCountIs(int count, Pageable pageable); @Query(“从“ Book book”中选择一本书,左加入book.authors,其中book.authors.size ==?1”)列表findAllByAuthorsCountIs(int count,Pageable pageable);
Hope this helps: 希望这可以帮助:
@Repository
public interface BookRepository extends PagingAndSortingRepository<Book, Integer> {
@Query("select b from Book b left join b.authors a group by b.id having count(b) = ?1 ")
List<Book> findAllByAuthorsCountIs(long count, Pageable pageable);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.