Spring Data JPA And NamedEntityGraphs

前端 未结 5 647
挽巷
挽巷 2020-11-28 04:44

currently I am wrestling with being able to fetch only the data I need. The findAll() method needs to fetch data dependant on where its getting called. I do not want to end

5条回答
  •  广开言路
    2020-11-28 05:42

    Using the @EntityGraph annotation on a derived query is possible, as I found out from This article. The article has the example:

    @Repository
    public interface ArticleRepository extends JpaRepository {
       @EntityGraph(attributePaths = "topics")
       Article findOneWithTopicsById(Long id);
    }
    

    But I don't think there's anything special about "with" and you can actually have anything between find and By. I tried these and they work (this code is Kotlin, but the idea is the same):

    interface UserRepository : PagingAndSortingRepository {
        @EntityGraph(attributePaths = arrayOf("address"))
        fun findAnythingGoesHereById(id: Long): Optional
    
        @EntityGraph(attributePaths = arrayOf("address"))
        fun findAllAnythingGoesHereBy(pageable: Pageable): Page
    }
    
    

    The article had mentioned the caveat that you can't create a method similar to findAll which will query all records without having a By condition and uses findAllWithTopicsByIdNotNull() as an example. I found that just including By by itself at the end of the name was sufficient: findAllWithTopicsBy(). A little more terse but maybe a little more confusing to read. Using method names which end with just By without any condition may be in danger of breaking in future versions in Spring since it doesn't seem like an intended use of derived queries name.

    It looks like the code for parsing derived query names in Spring is here on github. You can look there in case you're curious about what's possible for derived queries repository method names.

    These are the spring docs for derived queries.

    This was tested with spring-data-commons-2.2.3.RELEASE

提交回复
热议问题