将特定查询转换为JPQL或Criteria Builder查询

问题描述 投票:0回答:1

这里是2个实体的代码(它在数据库中生成三个表)。 Book实体:

@Entity
public class Book {
    @Id
    private long id;

    private String name;

    @ManyToMany
    private List<Author> authors;
}

Author实体:

@Entity
public class Author {
    @Id
    private long id;

    @Column(unique=true)
    private String name;
}

我正在尝试按作者列表查找书籍。这是一个SQL查询:

select book.id, ARRAY_AGG(author.name)
from book 
join book_authors ba on book.id=ba.book_id 
join author on ba.authors_id=author.id
group by book.id
having  ARRAY_AGG(distinct author.name order by author.name)=ARRAY['a1', 'a2']::varchar[]

['a1', 'a2']是书籍作者的列表,必须将其作为参数传递。想法是汇总作者,然后将其与传递的参数列表进行比较。

如何将此SQL查询重写为JPQL或CriteriaBuilder查询?

spring-data-jpa jpql hibernate-criteria
1个回答
0
投票

应该这样做:

@Repository
public interface BookRepository extends JpaRepository<Book, Long> {

    List<Book> findAllByAuthorsNameIn(List<String> names)

}

这里是有关如何编写查询的文档:https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-methods.query-creation

© www.soinside.com 2019 - 2024. All rights reserved.