hibernatejpaspring-data-jpaspring-dataentitygraph

Named Entity Graphs Naming Scope in Spring Data


I've recently discovered Named Entity Graphs, and I'm trying to implement them in a clean, DRY way.

What I'm not sure about (and reading through the JPA and Spring Data Docs hasn't answered) is the scope of the names used. Are the private to the classes they're defined in, or can I do something like this:

@Entity
@NamedEntityGraphs({
        @NamedEntityGraph(name = "Route.deep",
        attributeNodes = {
                @NamedAttributeNode(value = "stops", subgraph = "Stop.deep ")
        })
})
public class Route { ... }

@Entity
@NamedEntityGraphs({
        @NamedEntityGraph(name = "Stop.deep",
        attributeNodes = {
                @NamedAttributeNode(value = "records")
        })
})
public class Stop{ ... }

Where the Stop.deep subgraph in Route refers to the named entity graph in Stop.

Thanks!


Solution

  • An EntityGraph is obtained from the EntityManager without defining any kind of scope. => There is no scope for an EntityGraph in this sense.

    But named entity graphs are bound to the entity type they are defined on. From the JPA spec (10.3.1):

    The NamedEntityGraph annotation must be applied to the entity class that forms the root of the corresponding graph of entities.

    And subgraphs are bound to the type they apply to (not to the type they are referenced from. See JPA spec (10.3.3).

    Since Spring Data JPA just offers some convenience API for this feature.

    For reference: https://docs.oracle.com/javaee/7/tutorial/persistence-entitygraphs003.htm