Java Code Examples for javax.persistence.EntityGraph#addSubgraph()

The following examples show how to use javax.persistence.EntityGraph#addSubgraph() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: StaticEntityRepositoryImpl.java    From we-cmdb with Apache License 2.0 6 votes vote down vote up
private void queryJoin(CriteriaBuilder cb, CriteriaQuery query, From from, FilterPath path, EntityGraph<?> eg, Subgraph sg, List<Predicate> predicates) {
    String joinAttr = path.getJoinAttr();
    From joinPath = null;
    if (".".equals(joinAttr)) {
        joinPath = from;
    } else {
        if (sg == null) {
            sg = eg.addSubgraph(path.getJoinAttr());
        } else {
            sg = sg.addSubgraph(path.getJoinAttr());
        }
        joinPath = from.join(path.getJoinAttr());
    }
    applyFilter(cb, query, path.getFilters(), joinPath, predicates);
    if (path.getJoinChildren() != null && path.getJoinChildren().size() > 0) {
        for (FilterPath fp : path.getJoinChildren()) {
            queryJoin(cb, query, joinPath, fp, eg, sg, predicates);
        }
    }
}
 
Example 2
Source File: PhoneBookService.java    From jpa-addressbook with The Unlicense 6 votes vote down vote up
/**
 * 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;
}
 
Example 3
Source File: AccountDAO.java    From Hands-On-High-Performance-with-Spring-5 with MIT License 5 votes vote down vote up
@Override
public Account findAccountUsingDynamicEntityGraph(Long accountId) {
	EntityGraph<?> entityGraph =  getEntityManager().createEntityGraph(Account.class);
	entityGraph.addSubgraph("transactions");
	
	Map<String, Object> hints = new HashMap<String, Object>();
	hints.put("javax.persistence.fetchgraph", entityGraph);
	return this.getEntityManager().find(Account.class, accountId, hints);
}
 
Example 4
Source File: EntityGraphBuilderImpl.java    From crnk-framework with Apache License 2.0 5 votes vote down vote up
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.getLast().getName());
	} else {
		return graph.addSubgraph(fetchPath.toString());
	}
}
 
Example 5
Source File: SignInService.java    From bouncr with Eclipse Public License 1.0 5 votes vote down vote up
public Map<String, List<String>> getPermissionsByRealm(User user) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Assignment> assignmentCriteria = cb.createQuery(Assignment.class);
    Root<Assignment> assignmentRoot = assignmentCriteria.from(Assignment.class);
    Join<Group, Assignment> groupJoin = assignmentRoot.join("group");
    Join<User, Group> userJoin = groupJoin.join("users");
    assignmentRoot.fetch("role").fetch("permissions");
    assignmentCriteria.where(cb.equal(userJoin.get("id"), user.getId()));

    EntityGraph<Assignment> assignmentGraph = em.createEntityGraph(Assignment.class);
    assignmentGraph.addAttributeNodes("realm", "role");
    Subgraph<Role> roleGraph = assignmentGraph.addSubgraph("role");
    roleGraph.addAttributeNodes("permissions");
    Subgraph<Permission> permissionsGraph = roleGraph.addSubgraph("permissions");
    permissionsGraph.addAttributeNodes("name");

    return em.createQuery(assignmentCriteria)
            .setHint("javax.persistence.cache.storeMode", CacheStoreMode.REFRESH)
            .setHint("javax.persistence.fetchgraph", assignmentGraph)
            .getResultStream()
            .collect(Collectors.groupingBy(Assignment::getRealm))
            .entrySet()
            .stream()
            .collect(Collectors.toMap(
                    e -> e.getKey().getId().toString(),
                    e -> new ArrayList<>(e.getValue().stream()
                            .flatMap(v -> v.getRole().getPermissions().stream())
                            .map(Permission::getName)
                            .collect(Collectors.toSet()))));
}
 
Example 6
Source File: AbstractQueryExecutorImpl.java    From katharsis-framework with Apache License 2.0 5 votes vote down vote up
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());
	}
}
 
Example 7
Source File: ApplicationsResource.java    From bouncr with Eclipse Public License 1.0 4 votes vote down vote up
@Decision(HANDLE_OK)
public List<Application> handleOk(ApplicationSearchParams params, UserPermissionPrincipal principal, EntityManager em) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Application> query = cb.createQuery(Application.class);
    Root<Application> applicationRoot = query.from(Application.class);
    query.distinct(true);

    List<Predicate> predicates = new ArrayList<>();
    if (!principal.hasPermission("any_application:read")) {
        Join<User, Group> userJoin = applicationRoot.join("realms")
                .join("assignments")
                .join("group")
                .join("users");
        predicates.add(cb.equal(userJoin.get("id"), principal.getId()));
    }

    Optional.ofNullable(params.getQ())
            .ifPresent(q -> {
                String likeExpr = "%" + q.replaceAll("%", "_%") + "%";
                predicates.add(cb.like(applicationRoot.get("name"), likeExpr, '_'));
            });
    if (!predicates.isEmpty()) {
        query.where(predicates.toArray(Predicate[]::new));
    }

    List<ResourceField> embedEntities = some(params.getEmbed(), embed -> new ResourceFilter().parse(embed))
            .orElse(Collections.emptyList());
    EntityGraph<Application> applicationGraph = em.createEntityGraph(Application.class);
    applicationGraph.addAttributeNodes("name", "description", "passTo", "virtualPath", "topPage", "writeProtected");

    if (embedEntities.stream().anyMatch(r -> r.getName().equalsIgnoreCase("realms"))) {
        applicationGraph.addAttributeNodes("realms");
        Subgraph<Realm> realmsGraph = applicationGraph.addSubgraph("realms");
        realmsGraph.addAttributeNodes("name", "description", "url");
    }

    return em.createQuery(query)
            .setHint("javax.persistence.fetchgraph", applicationGraph)
            .setFirstResult(params.getOffset())
            .setMaxResults(params.getLimit())
            .getResultList();
}
 
Example 8
Source File: UserResource.java    From bouncr with Eclipse Public License 1.0 4 votes vote down vote up
@Decision(EXISTS)
public boolean exists(Parameters params, RestContext context, EntityManager em) {
    CriteriaBuilder builder = em.getCriteriaBuilder();
    CriteriaQuery<User> query = builder.createQuery(User.class);
    Root<User> userRoot = query.from(User.class);
    userRoot.fetch("userProfileValues", JoinType.LEFT);
    query.where(builder.equal(userRoot.get("account"), params.get("account")));

    List<ResourceField> embedEntities = some(params.get("embed"), embed -> new ResourceFilter().parse(embed))
            .orElse(Collections.emptyList());

    EntityGraph<User> userGraph = em.createEntityGraph(User.class);
    userGraph.addAttributeNodes("account", "userProfileValues");
    if (embedEntities.stream().anyMatch(r -> r.getName().equalsIgnoreCase("groups"))) {
        userRoot.fetch("groups", JoinType.LEFT);
        query.distinct(true);
        userGraph.addAttributeNodes("groups");
        userGraph.addSubgraph("groups")
                .addAttributeNodes("name", "description");
    }

    // OIDC provider
    if (embedEntities.stream().anyMatch(r -> r.getName().equalsIgnoreCase("oidc_providers"))) {
        userRoot.fetch("oidcUsers", JoinType.LEFT);
        userGraph.addAttributeNodes("oidcUsers");
        Subgraph<Object> oidcUsersGraph = userGraph.addSubgraph("oidcUsers");
        oidcUsersGraph.addSubgraph("oidcProvider")
                .addAttributeNodes("name");
    }

    User user = em.createQuery(query)
            .setHint("javax.persistence.cache.storeMode", CacheStoreMode.REFRESH)
            .setHint("javax.persistence.fetchgraph", userGraph)
            .getResultStream().findAny().orElse(null);

    if (user != null) {
        final UserProfileService userProfileService = new UserProfileService(em);
        final List<UserProfileVerification> userProfileVerifications = userProfileService.findUserProfileVerifications(user.getAccount());
        user.setUnverifiedProfiles(userProfileVerifications.stream()
                .map(UserProfileVerification::getUserProfileField)
                .filter(Objects::nonNull)
                .map(UserProfileField::getJsonName)
                .collect(Collectors.toList()));
        context.putValue(user);
    }
    return user != null;
}
 
Example 9
Source File: AllAssociationTest.java    From POC with Apache License 2.0 4 votes vote down vote up
@Test
@Transactional
void testAllAssociations() {
	Post post = new Post();
	post.setTitle("Postit");

	PostComment comment1 = new PostComment();
	comment1.setReview("Good");

	PostComment comment2 = new PostComment();
	comment2.setReview("Excellent");

	post.addComment(comment1);
	post.addComment(comment2);

	PostDetails postDetails = new PostDetails();
	postDetails.setCreatedBy("JUNIT");
	post.addDetails(postDetails);

	this.entityManager.persist(post);

	// 1. Use Criteria Builder to create a Criteria Query returning the
	// expected result object
	CriteriaBuilder builder = this.entityManager.getCriteriaBuilder();
	CriteriaQuery<Post> query = builder.createQuery(Post.class);

	// 2. Define roots for tables which are involved in the query
	Root<Post> postRoot = query.from(Post.class);

	// 3. Define Predicates etc using Criteria Builder
	Predicate cond = builder.equal(postRoot.get("title"), "post");

	// 4. Add Predicates etc to the Criteria Query
	query.where(cond);

	// 5. Build the TypedQuery using the entity manager and criteria query
	TypedQuery<Post> q = this.entityManager.createQuery(query);
	List<Post> resultList = q.getResultList();

	assertThat(resultList).isEmpty();

	// Retrieving the data by joining and using EntityGraph

	CriteriaQuery<Post> query1 = builder.createQuery(Post.class);
	// 2. Define roots for tables which are involved in the query
	Root<Post> root1 = query1.from(Post.class);

	// 3. Define Predicates etc using Criteria Builder, comments should be available
	// in post entity
	Join<Post, PostComment> join = root1.join("comments", JoinType.LEFT);
	// 4. Add Predicates etc to the Criteria Query
	query1.select(root1).where(builder.equal(join.get("review"), "Excellent"));

	// 5. Creating EntityGraphs
	EntityGraph<Post> fetchGraph = this.entityManager.createEntityGraph(Post.class);
	fetchGraph.addSubgraph("comments");

	// 6. Build the TypedQuery using the entity manager and criteria query
	TypedQuery<Post> q1 = this.entityManager.createQuery(query1).setHint("javax.persistence.loadgraph", fetchGraph);
	resultList = q1.getResultList();
	assertThat(resultList).isNotEmpty().size().isGreaterThanOrEqualTo(1);

}