Java Magazine, May/June 2018
ORACLE COM JAVAMAGAZINE MAY JUNE 2018 33 design patterns As you can see Hibernate not only selects the database columns mapped by the Department entity but also selects all columns mapped by the Employee entity within the same query Thats a lot faster than executing an additional query to initialize the association for each selected Department entity Initialize associations with a NamedEntityGraph If you load an entity via the find method of your EntityManager or if youre looking for a reusable way to define the fetching behavior you can use a NamedEntityGraph It was introduced in JPA 21 and provides an annotation based approach to define a graph of entities that will be fetched from the database Heres a simple example of a NamedEntityGraph that fetches all Employee entities associated with a Department entity @ NamedEntityGraph name graph DepartmentEmployee attributeNodes @ NamedAttributeNode employees After you have defined your NamedEntityGraph you can use a query hint to tell your persistence provider to use it as a fetchgraph with your query or your call of the EntityManager find method Map String Object hints new HashMap hints put javax persistence fetchgraph em getEntityGraph graph DepartmentEmployee Department d em find Department class 1L hints The generated SQL statement is similar to the one generated for the previously explained JPQL query 18 25 35150 DEBUG org hibernate SQL select department0_ id as id1_ 0_ 0_
You must have JavaScript enabled to view digital editions.