How to Fetch Data using Spring Data

前端 未结 1 911
北恋
北恋 2021-01-26 04:34

Hey i want to create a repository extending JpaRepository and fetch result without writing actual query, In my example i have 2 tables Book and Author mapped by many to many re

相关标签:
1条回答
  • 2021-01-26 04:53

    You want to find all books for a specific author so, given an Author, retrieve all Books whose set of Authors contains the specified Author.

    The relevant JPQL operator is:

    http://www.objectdb.com/java/jpa/query/jpql/collection#NOT_MEMBER_OF_

    [NOT] MEMBER [OF] The [NOT] MEMBER OF operator checks if a specified element is contained in a specified persistent collection field.

    For example:

    'English' MEMBER OF c.languages is TRUE if languages contains 'English' and FALSE if not. 'English' NOT MEMBER OF c.languages is TRUE if languages does not contain 'English'.

    As you may (or may not) be aware, you are using Spring Data which can derive some queries for you depending on method name. The docs do not however mention support for the [NOT] MEMBER [OF] operator:

    http://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-methods.query-creation

    You will therefore need to add a custom query method to your repository which will look something like:

    public interface BookRepository extends JpaRepository<Book, Integer> {
    
        @Query("select b from Book b where ?1 MEMBER OF b.authors")
        List<Book> findByAuthor(Author author);
    }
    

    and where the Author passed as a parameter is a persistent instance retrieved from the Database (via your AuthorRepository).

    0 讨论(0)
提交回复
热议问题