JPA inheritance @EntityGraph include optional associations of subclasses

后端 未结 4 893
广开言路
广开言路 2021-02-19 01:48

Given the following domain model, I want to load all Answers including their Values and their respective sub-children and put it in an AnswerDTO<

4条回答
  •  别那么骄傲
    2021-02-19 02:05

    My latest project used GraphQL (a first for me) and we had a big issue with N+1 queries and trying to optimize the queries to only join for tables when they are required. I have found Cosium / spring-data-jpa-entity-graph irreplaceable. It extends JpaRepository and adds methods to pass in an entity graph to the query. You can then build dynamic entity graphs at runtime to add in left joins for only the data you need.

    Our data flow looks something like this:

    1. Receive GraphQL request
    2. Parse GraphQL request and convert to list of entity graph nodes in the query
    3. Create entity graph from the discovered nodes and pass into the repository for execution

    To solve the problem of not including invalid nodes into the entity graph (for example __typename from graphql), I created a utility class which handles the entity graph generation. The calling class passes in the class name it is generating the graph for, which then validates each node in the graph against the metamodel maintained by the ORM. If the node is not in the model, it removes it from the list of graph nodes. (This check needs to be recursive and check each child as well)

    Before finding this I had tried projections and every other alternative recommended in the Spring JPA / Hibernate docs, but nothing seemed to solve the problem elegantly or at least with a ton of extra code

提交回复
热议问题