我有2个实体:书籍和作者。每个映射到适当的表。我还有第三张表convertToComponent<Component_CheckDelete>(rendererPtr)->ToBeDeleted==true
,因为这两个实体具有多对多关系。我需要从数据库中选择作者人数等于book_author
的所有书籍。
图书:
count
作者:
@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<>();
...
}
我想得到这样的东西:
@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<>();
...
}
请告诉我我怎么能得到这个。
答案 0 :(得分:1)
您可以在Hql查询中使用集合大小。
例如...
从Book book左侧加入book.authors,其中book.authors.size == 3
有关更多信息,请参见下面的链接...
https://docs.jboss.org/hibernate/core/3.3/reference/en/html/queryhql.html
@Query(“从书本左侧选择书本加入book.authors,其中book.authors.size ==?1”) 列出findAllByAuthorsCountIs(int count,Pageable pageable);
答案 1 :(得分:0)
希望这会有所帮助:
@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);
}