Hibernate JPA @NamedSubgraph Example

@NamedSubgraph

The @NamedSubgraph annotation used to specify a subgraph in an Entity Graph.

NamedSubgraph
A NamedSubgraph is a member element of a NamedEntityGraph. The NamedSubgraph is only referenced from within a NamedEntityGraph and can not be referenced independently. It is referenced by its name from a NamedAttributeNode element of the NamedEntityGraph.


A sub-graph is used to control the fetching of sub-attributes of the AttributeNode it is applied to. It is generally defined via the @NamedSubgraph annotation.

If we have a Project parent entity which has an employees child associations, and we’d like to fetch the department for the Employee child association.

Fetch graph with a subgraph mapping

@Entity(name = "Project")
@NamedEntityGraph(name = "project.employees",
attributeNodes = @NamedAttributeNode(
value = "employees",
subgraph = "project.employees.department"
),
subgraphs = @NamedSubgraph(
name = "project.employees.department",
attributeNodes = @NamedAttributeNode( "department" )
)
)
public static class Project {

@Id
private Long id;

@ManyToMany
private List<Employee> employees = new ArrayList<>();

//Getters and setters omitted for brevity
}
When fetching this entity graph, Hibernate generates the following SQL query:

Fetch graph with a subgraph mapping

Project project = doInJPA( this::entityManagerFactory, entityManager -> {
return entityManager.find(
Project.class,
1L,
Collections.singletonMap(
"javax.persistence.fetchgraph",
entityManager.getEntityGraph( "project.employees" )
)
);
} );

Comments

Popular posts from this blog

Today Walkin 14th-Sept

Hibernate Search - Elasticsearch with JSON manipulation

Spring Elasticsearch Operations