Named entity graph

Then named entity graph is a new feature, introduced in JPA 2.1. In this approach, we can define a graph of entities that need to be queried from the database. We can define the entity graph on our entity class by using the @NamedEntityGraph annotation.

The following is an example of how to define a graph using @NamedEntityGraph on the entity class:

@Entity
@NamedEntityGraph(name="graph.transactions", attributeNodes= @NamedAttributeNode("transactions"))
public class Account implements Serializable {

private static final long serialVersionUID = 1232821417960547743L;

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "account_id", updatable = false, nullable = false)
private Long accountId;
private String name;

@OneToMany(mappedBy = "account", fetch=FetchType.LAZY)
private List<Transaction> transactions = new ArrayList<Transaction>
();
.....
}

An entity graph definition is independent of the query and defines which attributes to be fetched from the database. An entity graph can be used as a load or a fetch graph. If a load graph is used, all attributes that are not specified in the entity graph definition will keep following their default FetchType. If a fetch graph is used, only the attributes specified by the entity graph definition will be treated as FetchType.EAGER, and all other attributes will be treated as LAZY. The following is an example of how to use a named entity graph as a fetchgraph:

EntityGraph<?> entityGraph = getEntityManager().createEntityGraph("graph.transactions");
Query query = getEntityManager().createQuery("SELECT a FROM Account AS a WHERE a.accountId=:accountId", Account.class);

query.setHint("javax.persistence.fetchgraph", entityGraph);
query.setParameter("accountId", accountId);
return (Account)query.getSingleResult();

We are not going to go into detail on named entity graphs in this book. This is one of the best approaches to resolve the n + 1 issue with Hibernate. This is an improved version of JOIN FETCH. An advantage on top of JOIN FETCH is that it will be reused for different use cases. The only disadvantage of this approach is that we must annotate the named entity graph for each combination of associations that we want to fetch in a single query. So, this can get quite messy if we have too many different combinations to set.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset