Skip to content

Instantly share code, notes, and snippets.

@gsitgithub
Forked from thjanssen/defineNamedGraph.java
Created August 30, 2018 12:18
Show Gist options
  • Save gsitgithub/dc8cd4123b8613365534ebf860d2b3f2 to your computer and use it in GitHub Desktop.
Save gsitgithub/dc8cd4123b8613365534ebf860d2b3f2 to your computer and use it in GitHub Desktop.
5 ways to initialize lazy relations and when to use them (http://www.thoughts-on-java.org/2014/12/5-ways-to-initialize-lazy-relations.html)
@Entity
@NamedEntityGraph(name = "graph.Order.items",
attributeNodes = @NamedAttributeNode("items"))
public class Order implements Serializable {
....
EntityGraph graph = this.em.createEntityGraph(Order.class);
Subgraph itemGraph = graph.addSubgraph("items");
Map hints = new HashMap();
hints.put("javax.persistence.loadgraph", graph);
Order order = this.em.find(Order.class, orderId, hints);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery q = cb.createQuery(Order.class);
Root o = q.from(Order.class);
o.fetch("items", JoinType.INNER);
q.select(o);
q.where(cb.equal(o.get("id"), orderId));
Order order = (Order)this.em.createQuery(q).getSingleResult();
Query q = this.em.createQuery("SELECT o FROM Order o JOIN FETCH o.items i WHERE o.id = :id");
q.setParameter("id", orderId);
newOrder = (Order) q.getSingleResult();
Order order = this.em.find(Order.class, orderId);
order.getItems().size();
EntityGraph graph = this.em.getEntityGraph("graph.Order.items");
Map hints = new HashMap();
hints.put("javax.persistence.fetchgraph", graph);
Order order = this.em.find(Order.class, orderId, hints);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment