gpt4 book ai didi

java - Spring Data JPA : query ManyToMany, 按计数选择

转载 作者:行者123 更新时间:2023-12-02 09:33:34 24 4
gpt4 key购买 nike

我有 2 个实体:书籍和作者。每个都映射到适当的表。我还有第三个表 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<>();
...
}

我想要得到类似的东西:

    @Repository
public interface BookRepository extends PagingAndSortingRepository<Book, Integer> {
List<Book> findAllByAuthorsCountIs(int count, Pageable pageable);
}

请告诉我如何获得这个。

最佳答案

您可以在 Hql 查询中使用集合大小。

例如...

从 Book book left 加入 book.authors 其中 book.authors.size == 3

欲了解更多信息,请参阅以下链接...

https://docs.jboss.org/hibernate/core/3.3/reference/en/html/queryhql.html

@Query("从图书中选择图书 book left join book.authors where book.authors.size == ?1") 列表 findAllByAuthorsCountIs(int count, Pageable 可分页);

关于java - Spring Data JPA : query ManyToMany, 按计数选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57743272/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com