private static void addAttributeNodes(String fieldName, EntityGraph<?> graph) { int pos = fieldName.indexOf(GRAPH_DELIMETER); if (pos < 0) { graph.addAttributeNodes(fieldName); return; } String subgraphName = fieldName.substring(0, pos); Subgraph<?> subGraph = graph.addSubgraph(subgraphName); String nextFieldName = fieldName.substring(pos + 1); pos = nextFieldName.indexOf(GRAPH_DELIMETER); while (pos > 0) { subgraphName = nextFieldName.substring(0, pos); subGraph = graph.addSubgraph(subgraphName); nextFieldName = nextFieldName.substring(pos + 1); pos = nextFieldName.indexOf(GRAPH_DELIMETER); } subGraph.addAttributeNodes(nextFieldName); }
@Override public List<E> findAllWithAttributes(String... attributes) { // String sql = "SELECT o FROM " + getTableName() + " o"; EntityGraph<E> graph = entityManager.createEntityGraph(getEntityClass()); graph.addAttributeNodes(attributes); // TypedQuery<E> query = entityManager.createQuery(sql, getEntityClass()); // query.setHint("javax.persistence.loadgraph", graph); // TypedQuery<E> query = entityManager.createQuery(sql, getEntityClass()); // LoadGroup lg = new LoadGroup(); // lg.addAttributes(Arrays.asList(attributes)); // query.setHint(QueryHints.LOAD_GROUP, lg); // for (String att : attributes) { // query.setHint(QueryHints.BATCH, "o." + att); // } // List<E> result = query.getResultList(); List<E> result = findAllWithGraph(graph); return result; }
@SuppressWarnings("unchecked") @Test public void selectWithEntityGraph() { log.info("... selectWithEntityGraph ..."); EntityManager em = emf.createEntityManager(); em.getTransaction().begin(); EntityGraph<Author> graph = em.createEntityGraph(Author.class); graph.addAttributeNodes(Author_.books); TypedQuery<Author> q = em.createQuery("SELECT a FROM Author a WHERE a.id = 1", Author.class); q.setHint("javax.persistence.fetchgraph", graph); Author a = q.getSingleResult(); em.getTransaction().commit(); em.close(); log.info(a.getFirstName()+" "+a.getLastName()+" wrote "+a.getBooks().size()+" books."); }
@Test public void selectWithNamedEntityGraph() { log.info("... selectWithNamedEntityGraph ..."); EntityManager em = emf.createEntityManager(); em.getTransaction().begin(); EntityGraph<?> graph = em.createEntityGraph("graph.AuthorBooks"); TypedQuery<Author> q = em.createQuery("SELECT a FROM Author a WHERE a.id = 1", Author.class); q.setHint("javax.persistence.fetchgraph", graph); Author a = q.getSingleResult(); em.getTransaction().commit(); em.close(); log.info(a.getFirstName()+" "+a.getLastName()+" wrote "+a.getBooks().size()+" books."); }
/** * {@inheritDoc} */ @Override public DocumentRouteHeaderValue getMinimalRouteHeader(String documentId) { // This graph is defined on the DocumentRouteHeaderValue class. EntityGraph<DocumentRouteHeaderValue> entityGraph = (EntityGraph<DocumentRouteHeaderValue>) entityManager.createEntityGraph("DocumentRouteHeaderValue.ActionListAttributesOnly"); TypedQuery<DocumentRouteHeaderValue> query = entityManager.createQuery("SELECT rh FROM DocumentRouteHeaderValue rh WHERE rh.documentId = :documentId", DocumentRouteHeaderValue.class ); // By using the graph - all properties but those on the graph should have // a lazy proxy in place. Attempting to access any of those *should* cause the // rest of the properties to load. query.setHint("javax.persistence.fetchgraph", entityGraph); query.setParameter("documentId", documentId); List<DocumentRouteHeaderValue> result = query.getResultList(); if ( result.isEmpty() ) { return null; } return result.get(0); }
/** * Fetches an instance of given PhoneBookEntry with all lazy * loaded properties loaded. * @param entry * @return the fully loaded instance */ public PhoneBookEntry loadFully(PhoneBookEntry entry) { // To get lazy loaded fields initialized, you have couple of options, // all with pros and cons, 3 of them presented here. // 1) use an explicit join query (with EntityManager or @Query annotation // in repository method. // em.createQuery("select e from PhoneBookEntry e LEFT JOIN FETCH e.groups where e.id = :id", PhoneBookEntry.class); // ... // 2) use EntityGraph's introduced in JPA 2.1, here constructed dynamically // and passed via QueryResult object from DeltaSpike Data. You can // also use entity graphs with @Query annotation in repositories or // with raw EntityManager API. EntityGraph<PhoneBookEntry> graph = this.em.createEntityGraph( PhoneBookEntry.class); graph.addSubgraph("groups"); entry = entryRepo.findById(entry.getId()) .hint("javax.persistence.loadgraph", graph) .getSingleResult(); // 3) ..or use the infamous size() hack that all of us actually do :-) entry.getAddresses().size(); return entry; }
/** * Suche nach Kunden �ber Nachnamen * @param name Der angegebene Nachname * @return Liste der Kunden, die den angegebenen Nachnamen besitzen */ @NotNull(message = "{kunde.notFound.name}") public List<Kunde> findKundenByNachname(String name, FetchType fetchType) { final TypedQuery<Kunde> query = em.createNamedQuery(Kunde.FIND_KUNDEN_BY_NACHNAME, Kunde.class) .setParameter(Kunde.PARAM_KUNDE_NACHNAME, name); EntityGraph<?> entityGraph; switch(fetchType) { case NUR_KUNDE: break; case MIT_BESTELLUNGEN: entityGraph = em.getEntityGraph(Kunde.GRAPH_BESTELLUNGEN); query.setHint(LOADGRAPH, entityGraph); break; default: break; } return query.getResultList(); }
/** * Suche nach Liste aller Kunden * @return Gibt alle vorhandenen Kunden zur�ck */ public List<Kunde> findAllKunden(FetchType fetchType, OrderType orderType) { final TypedQuery<Kunde> query = OrderType.ID.equals(orderType) ? em.createNamedQuery(Kunde.FIND_KUNDEN_ORDER_BY_ID, Kunde.class) : em.createNamedQuery(Kunde.FIND_KUNDEN, Kunde.class); EntityGraph<?> entityGraph; switch(fetchType) { case NUR_KUNDE: break; case MIT_BESTELLUNGEN: entityGraph = em.getEntityGraph(Kunde.GRAPH_BESTELLUNGEN); query.setHint(LOADGRAPH, entityGraph); break; default: break; } return query.getResultList(); }
/** * Build or return the default Entity Graph that represents defaultExpand * * @param session * * @return */ public EntityGraph getDefaultGraph(final Session session) { if (this.defaultExpandGraph == null) { final EntityGraph<?> graph = session.createEntityGraph(clazz); populateGraph(graph, getEagerFetch()); this.defaultExpandGraph = graph; return graph; } else { return this.defaultExpandGraph; } }
@Test @InSequence(5) public void shouldLoadArtistWithLiveConcertsAndContracts() throws Exception{ EntityGraph artistGraph = em.getEntityGraph("Artist.WithConcertsAndContracts"); PersistenceUnitUtil util = em.getEntityManagerFactory().getPersistenceUnitUtil(); Artist artist = getArtistWithEntityGraph( "Artist.WithConcertsAndContracts"); System.out.printf("++++ artist=%s\n", artist); assertTrue(util.isLoaded(artist, "id")); assertTrue(util.isLoaded(artist, "name")); assertTrue(util.isLoaded(artist, "events")); ConcertEvent event = artist.getEvents().values().iterator().next(); System.out.printf("++++ concert event=%s\n", event ); assertTrue(util.isLoaded(event, "id")); assertTrue(util.isLoaded(event, "name")); assertTrue(util.isLoaded(event, "eventType")); assertTrue(util.isLoaded(event, "contracts")); }
@Test @InSequence(2) public void shouldLoadArtistWithoutConcerts() throws Exception{ PersistenceUnitUtil util = em.getEntityManagerFactory().getPersistenceUnitUtil(); EntityGraph artistGraph = em.getEntityGraph("Artist.NoConcerts"); Artist artist = (Artist) em.createQuery("Select a from Artist a") .setHint("javax.persistence.fetchgraph", artistGraph) .getResultList() .get(0); System.out.printf("++++ artist=%s\n", artist); System.out.printf(">> loaded artist.id = %s\n", util.isLoaded(artist, "id")); System.out.printf(">> loaded artist.name = %s\n", util.isLoaded(artist, "name")); System.out.printf(">> loaded artist.events = %s\n", util.isLoaded(artist, "events")); assertTrue(util.isLoaded(artist, "id")); assertTrue(util.isLoaded(artist, "name")); assertFalse(util.isLoaded(artist, "events")); }
@Test @InSequence(3) public void shouldLoadArtistWithConcerts() throws Exception{ PersistenceUnitUtil util = em.getEntityManagerFactory().getPersistenceUnitUtil(); EntityGraph artistGraph = em.getEntityGraph("Artist.WithConcerts"); Artist artist = (Artist) em.createQuery("Select a from Artist a") .setHint("javax.persistence.fetchgraph", artistGraph) .getResultList() .get(0); System.out.printf("++++ artist=%s\n", artist); System.out.printf("artist=%s\n", artist); assertTrue(util.isLoaded(artist, "id")); assertTrue(util.isLoaded(artist, "name")); assertTrue(util.isLoaded(artist, "events")); }
@Test @InSequence(4) public void shouldLoadArtistWithLiveConcertsAndNoContracts() throws Exception { PersistenceUnitUtil util = em.getEntityManagerFactory().getPersistenceUnitUtil(); em.clear(); EntityGraph artistGraph = em.getEntityGraph( "Artist.WithConcertsAndNoContracts"); Artist artist = (Artist) em.createQuery("Select a from Artist a") .setHint("javax.persistence.fetchgraph", artistGraph) .getResultList() .get(0); System.out.printf("++++ artist=%s\n", artist); assertTrue(util.isLoaded(artist, "id")); assertTrue(util.isLoaded(artist, "name")); assertTrue(util.isLoaded(artist, "events")); ConcertEvent event = artist.getEvents().values().iterator().next(); System.out.printf("++++ concert event=%s\n", event ); assertTrue(util.isLoaded(event, "id")); assertTrue(util.isLoaded(event, "name")); assertTrue(util.isLoaded(event, "eventType")); assertFalse(util.isLoaded(event, "contracts")); }
@Test @InSequence(5) public void shouldLoadArtistWithLiveConcertsAndContracts() throws Exception{ PersistenceUnitUtil util = em.getEntityManagerFactory().getPersistenceUnitUtil(); em.clear(); EntityGraph artistGraph = em.getEntityGraph("Artist.WithConcertsAndContracts"); Artist artist = (Artist) em.createQuery("Select a from Artist a") .setHint("javax.persistence.fetchgraph", artistGraph) .getResultList() .get(0); System.out.printf("++++ artist=%s\n", artist); assertTrue(util.isLoaded(artist, "id")); assertTrue(util.isLoaded(artist, "name")); assertTrue(util.isLoaded(artist, "events")); ConcertEvent event = artist.getEvents().values().iterator().next(); System.out.printf("++++ concert event=%s\n", event ); assertTrue(util.isLoaded(event, "id")); assertTrue(util.isLoaded(event, "name")); assertTrue(util.isLoaded(event, "eventType")); assertTrue(util.isLoaded(event, "contracts")); }
@Override public <T> void build(EntityManager em, Query criteriaQuery, Class<T> entityClass, Set<MetaAttributePath> fetchPaths) { EntityGraph<T> graph = em.createEntityGraph(entityClass); for (MetaAttributePath fetchPath : fetchPaths) { applyFetchPaths(graph, fetchPath); } criteriaQuery.setHint("javax.persistence.fetchgraph", graph); }
private <T> Subgraph<Object> applyFetchPaths(EntityGraph<T> graph, MetaAttributePath fetchPath) { if (fetchPath.length() >= 2) { // ensure parent is fetched MetaAttributePath parentPath = fetchPath.subPath(0, fetchPath.length() - 1); Subgraph<Object> parentGraph = applyFetchPaths(graph, parentPath); return parentGraph.addSubgraph(fetchPath.toString()); } else { return graph.addSubgraph(fetchPath.toString()); } }
@Test public void testInitDynamicEntityGraph() { EntityGraph<User> graph = entityManager.createEntityGraph(User.class); graph.addAttributeNodes("cars"); User user = entityManager.find(User.class, 1L, Collections.singletonMap("javax.persistence.fetchgraph", graph)); user.getCars().stream().forEach(System.out::println); }
@Override public List<E> findAllWithGraph(EntityGraph<E> graph) { String sql = "SELECT o FROM " + getTableName() + " o"; TypedQuery<E> query = entityManager.createQuery(sql, getEntityClass()); query.setHint(QueryHints.JPA_LOAD_GRAPH, graph); return query.getResultList(); }
protected void applyFetchPaths(Query criteriaQuery) { EntityGraph<T> graph = em.createEntityGraph(getEntityClass()); for (MetaAttributePath fetchPath : fetchPaths) { applyFetchPaths(graph, fetchPath); } criteriaQuery.setHint("javax.persistence.fetchgraph", graph); }
private Subgraph<Object> applyFetchPaths(EntityGraph<T> graph, MetaAttributePath fetchPath) { if (fetchPath.length() >= 2) { // ensure parent is fetched MetaAttributePath parentPath = fetchPath.subPath(0, fetchPath.length() - 1); Subgraph<Object> parentGraph = applyFetchPaths(graph, parentPath); return parentGraph.addSubgraph(fetchPath.toString()); } else { return graph.addSubgraph(fetchPath.toString()); } }
@Override public <R> Page<R> findAll(Specification<T> spec, Class<R> projectionType, String namedEntityGraph, org.springframework.data.jpa.repository.EntityGraph.EntityGraphType type, Pageable pageable) { EntityGraph<?> entityGraph = this.entityManager.getEntityGraph(namedEntityGraph); if (entityGraph == null) { throw new IllegalArgumentException("Not found named entity graph -> " + namedEntityGraph); } TypedQuery<T> query = getQuery(spec, pageable); query.setHint(type.getKey(), entityGraph); return readPageWithProjection(spec, projectionType, pageable, query); }
@Test public void shouldLazyInitializationSolution5() { //encji Map<String, Object> hints = newHashMap(); EntityGraph<Item> itemGraph = em.createEntityGraph(Item.class); //<13> itemGraph.addAttributeNodes("offers"); //<14> hints.put("javax.persistence.loadgraph", itemGraph); //<15> em.getEntityGraphs(Item.class).forEach(eg->log.info("{}",eg)); Item one = em.find(Item.class, 1l,hints); assertThat(Persistence.getPersistenceUtil().isLoaded(one)).isTrue(); assertThat(Persistence.getPersistenceUtil().isLoaded(one.getOffers())).isTrue(); }
@Test public void shouldEntityGraphWork() { Map<String, Object> props = newHashMap(); EntityGraph<Skill> skillGraph = em.createEntityGraph(Skill.class); skillGraph.addAttributeNodes("candidate"); props.put("javax.persistence.loadgraph", skillGraph); Skill one = em.find(Skill.class, 1l, props); assertThat(Persistence.getPersistenceUtil().isLoaded(one)).isTrue(); assertThat(Persistence.getPersistenceUtil().isLoaded(one.getCandidate())).isTrue(); }
/** * Combines using an entityGraph for accessing data from a database with * dozer mapping and returns a decoupled data object * * @param em * entity manager for database access * @param classTypeBE * source object type * @param classTypeDO * destination object type * @param entityGraphName * name of the entity graph * @param id * identification number for accessed entity * @return data object of type classTypeDO */ public <BE, DO> DO useJEntityGraphDataMapper(final EntityManager em, final Class<BE> classTypeBE, final Class<DO> classTypeDO, final String entityGraphName, final int id) { final BuildDozerMapping dozerMappingBuilder = new BuildDozerMapping(); final BuildEntityGraph entityGraphBuilder = new BuildEntityGraph(); BE businessEntity = null; DO dataObject = null; try { dataObject = classTypeDO.newInstance(); } catch (InstantiationException | IllegalAccessException e) { e.printStackTrace(); } @SuppressWarnings("unchecked") final EntityGraph<BE> xmlGraph = (EntityGraph<BE>) entityGraphBuilder.generateEntityGraphXPath(em, entityGraphName, classTypeBE); final Map<String, Object> hints = new HashMap<String, Object>(); hints.put("javax.persistence.loadgraph", xmlGraph); businessEntity = em.find(classTypeBE, id, hints); final DozerBeanMapper mapper = dozerMappingBuilder.generateMappingRulesXPath(entityGraphName); mapper.map(businessEntity, dataObject); return dataObject; }
public List<User> findAllUsersWithPermissions() { CriteriaBuilder builder = getEntityManager().getCriteriaBuilder(); CriteriaQuery<User> query = builder.createQuery(User.class); CriteriaQuery<User> all = query.select(query.from(User.class)).distinct(true); EntityGraph<User> entityGraph = getEntityManager().createEntityGraph(User.class); entityGraph.addSubgraph("roles").addSubgraph("permissions"); return getEntityManager().createQuery(all).setHint("javax.persistence.loadgraph", entityGraph).getResultList(); }
/** * Suche einen Kunden zu gegebener ID * @param id Angegebene ID * @return Der Kunde, zu dem die gegebene ID geh�rt. */ @NotNull(message = "{kunde.notFound.id}") public Kunde findKundeById(Long id, FetchType fetchType) { if (id == null) return null; EntityGraph<?> entityGraph; Map<String, Object> props; Kunde kunde; switch (fetchType) { case NUR_KUNDE: kunde = em.find(Kunde.class, id); break; case MIT_BESTELLUNGEN: entityGraph = em.getEntityGraph(Kunde.GRAPH_BESTELLUNGEN); props = ImmutableMap.of(LOADGRAPH, (Object) entityGraph); kunde = em.find(Kunde.class, id, props); break; default: kunde = em.find(Kunde.class, id); break; } return kunde; }
@Override public <T> EntityGraph<T> createEntityGraph(final Class<T> rootType) { final Timer timer = Op.createEntityGraph.start(this.timer, this); try { return getEntityManager().createEntityGraph(rootType); } finally { timer.stop(); } }
@Override public EntityGraph<?> createEntityGraph(final String graphName) { final Timer timer = Op.createEntityGraph.start(this.timer, this); try { return getEntityManager().createEntityGraph(graphName); } finally { timer.stop(); } }
@Override public EntityGraph<?> getEntityGraph(final String graphName) { final Timer timer = Op.getEntityGraph.start(this.timer, this); try { return getEntityManager().getEntityGraph(graphName); } finally { timer.stop(); } }
@Override public <T> List<EntityGraph<? super T>> getEntityGraphs(final Class<T> entityClass) { final Timer timer = Op.getEntityGraphs.start(this.timer, this); try { return getEntityManager().getEntityGraphs(entityClass); } finally { timer.stop(); } }
@Override public <T> EntityGraph<T> createEntityGraph(Class<T> rootType) { logger.error("Thread: {} using entity Manager {}", Thread.currentThread().getId(), emid); return em.createEntityGraph(rootType); }
@Override public EntityGraph<?> createEntityGraph(String graphName) { logger.error("Thread: {} using entity Manager {}", Thread.currentThread().getId(), emid); return em.createEntityGraph(graphName); }
@Override public EntityGraph<?> getEntityGraph(String graphName) { logger.error("Thread: {} using entity Manager {}", Thread.currentThread().getId(), emid); return em.getEntityGraph(graphName); }
@Override public <T> List<EntityGraph<? super T>> getEntityGraphs(Class<T> entityClass) { logger.error("Thread: {} using entity Manager {}", Thread.currentThread().getId(), emid); return em.getEntityGraphs(entityClass); }
private Artist getArtistWithEntityGraph( String entityGraph) { EntityGraph artistGraph = em.getEntityGraph(entityGraph); return (Artist) em.createQuery("Select a from Artist a") .setHint("javax.persistence.fetchgraph", artistGraph) .getResultList() .get(0); }
private EntityGraph<T> createEnitityGraph(List<String> embed) { EntityGraph<T> graph = entityManager.createEntityGraph(domainClass); embed.forEach(f -> addAttributeNodes(f, graph)); return graph; }
public EntityGraphQueryHint(EntityGraph<?> originEntityGraph) { this.originEntityGraph = originEntityGraph; }
public EntityGraph getFetchGraph() { return fetchGraph; }