Spring Data JPA属性表达式可用于多对多查询

时间:2018-05-24 09:10:44

标签: spring spring-data spring-data-jpa jpa-2.0

我使用Spring boot 2,使用Spring数据& Spring Data JPA,我希望用Spring Data JPA替换一些现有的@Query方法Property Expressions

然而,我努力为多对多关系锻炼表达名称。我不太确定这是否可行,因为我所看到的所有例子都是基于一对多的关系。

一个基本的例子可能是:

图书实体

@Entity
@Table(name = "book")
public class Book {

    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "title")
    private String title;

    @ManyToMany(mappedBy = "authors", cascade = CascadeType.REFRESH, fetch = FetchType.LAZY)
    private Set<Author> authors = new HashSet<>();

    // Getter and Setters
}

作者实体

@Entity
@Table(name = "Author")
public class Author {

    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "forename")
    private String firstName;

    @Column(name = "surname")
    private String surname;

    @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    @JoinTable(
        name = "author_books",
        joinColumns = @JoinColumn(name = "author_id", referencedColumnName = "id"),
        inverseJoinColumns = @JoinColumn(name = "book_id", referencedColumnName = "id"),
        uniqueConstraints = @UniqueConstraint(columnNames = {"author_id", "book_id"})
    )
    private Set<Book> books = new HashSet<>();

    // Getter and Setters
}

当前的SQL查询如下所示:

SELECT *
FROM book
LEFT JOIN author_books ON author_books.book_id = book.id
WHERE author_books.author_id = 1;

如何在Book存储库中编写等效的Spring JPA Property Expressions(如果可能)?

我尝试了以下(没有运气):

List<Book> findByBooks_AuthorId(Long authorId);
List<Book> findByBooks_Author_Id(Long authorId);
List<Book> findByBooks_AuthorsId(Long authorId);
List<Book> findByBooks_Authors_Id(Long authorId);

一种解决方案是通过它的id获取作者对象,然后调用author.getBooks()。但是,我希望能够使用弹簧数据PageRequestSpecification类提供结果的过滤和分页。

任何帮助都会非常感激。

3 个答案:

答案 0 :(得分:0)

您需要的是通过作者的ID查找图书。因此,您需要将其写为方法的名称:

List<Book> findByAuthorsId(Long id);

就是这样! 如果目标列的名称与实体字段的名称相同,则也不必使用 @Column (name = ...)注释。 Property expressions

答案 1 :(得分:-1)

您是否尝试过使用Query Annotation? https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-methods.at-query

@Query("SELECT * FROM book LEFT JOIN author_books ON author_books.book_id = book.id WHERE author_books.author_id = ?1")
List<Book> findByBooks_AuthorId(Long authorId);

答案 2 :(得分:-1)

你可以试试这个:

List<Book> findAllByAuthorId(Author author);