All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.crnk.jpa.internal.query.EntityGraphBuilderImpl Maven / Gradle / Ivy

There is a newer version: 2.6.20180522184741
Show newest version
package io.crnk.jpa.internal.query;

import io.crnk.meta.model.MetaAttributePath;

import javax.persistence.EntityGraph;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.persistence.Subgraph;
import java.util.Set;

public class EntityGraphBuilderImpl implements EntityGraphBuilder {

	@Override
	public  void build(EntityManager em, Query criteriaQuery, Class entityClass,
						  Set fetchPaths) {
		EntityGraph graph = em.createEntityGraph(entityClass);
		for (MetaAttributePath fetchPath : fetchPaths) {
			applyFetchPaths(graph, fetchPath);
		}
		criteriaQuery.setHint("javax.persistence.fetchgraph", graph);
	}

	private  Subgraph applyFetchPaths(EntityGraph graph, MetaAttributePath fetchPath) {
		if (fetchPath.length() >= 2) {
			// ensure parent is fetched
			MetaAttributePath parentPath = fetchPath.subPath(0, fetchPath.length() - 1);
			Subgraph parentGraph = applyFetchPaths(graph, parentPath);
			return parentGraph.addSubgraph(fetchPath.toString());
		} else {
			return graph.addSubgraph(fetchPath.toString());
		}
	}
}