Java Code Examples for javax.persistence.EntityManager#createEntityGraph()

The following examples show how to use javax.persistence.EntityManager#createEntityGraph() . 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: TestEntityGraph.java    From HibernateTips with MIT License 8 votes vote down vote up
@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.");
}
 
Example 2
Source File: TestEntityGraph.java    From HibernateTips with MIT License 6 votes vote down vote up
@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.");
}
 
Example 3
Source File: EntityGraphBuilderImpl.java    From crnk-framework with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example 4
Source File: VerificationEmailResource.java    From bouncr with Eclipse Public License 1.0 5 votes vote down vote up
@Decision(PROCESSABLE)
public boolean processable(Parameters params, EntityManager em, RestContext context) {
    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")));

    EntityGraph<User> userGraph = em.createEntityGraph(User.class);
    userGraph.addAttributeNodes("account", "userProfileValues");

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

    if (user != null) {
        context.putValue(user);
    } else {
        context.setMessage(Problem.valueOf(422, "User not found"));
        return false;
    }

    UserProfileValue emailValue = findMailVerification(em, user.getAccount()).map(verification -> {
        context.putValue(verification);
        return verification;
    }).flatMap(verification -> user.getUserProfileValues()
            .stream()
            .filter(v -> Objects.equals(v.getUserProfileField().getJsonName(), "email"))
            .findAny()
            .filter(v -> Objects.nonNull(v.getValue()))
    ).orElse(null);

    if (emailValue != null) {
        context.putValue(emailValue);
    }
    return emailValue != null;
}
 
Example 5
Source File: ApplicationResource.java    From bouncr with Eclipse Public License 1.0 5 votes vote down vote up
@Decision(EXISTS)
public boolean exists(Parameters params, RestContext context, EntityManager em) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Application> query = cb.createQuery(Application.class);
    Root<Application> applicationRoot = query.from(Application.class);
    query.where(cb.equal(applicationRoot.get("name"), params.get("name")));

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

    EntityGraph<Application> applicationGraph = em.createEntityGraph(Application.class);
    applicationGraph.addAttributeNodes("name", "description", "virtualPath", "passTo", "topPage");

    if (embedEntities.stream().anyMatch(r -> r.getName().equalsIgnoreCase("realms"))) {
        applicationRoot.fetch("realms", JoinType.LEFT);
        query.distinct(true);
        applicationGraph.addSubgraph("realms")
                .addAttributeNodes("name", "description", "url");

    }

    Application application = em.createQuery(query)
            .setHint("javax.persistence.cache.storeMode", CacheStoreMode.REFRESH)
            .setHint("javax.persistence.fetchgraph", applicationGraph)
            .getResultStream().findAny().orElse(null);
    if (application != null) {
        context.putValue(application);
    }
    return application != null;
}
 
Example 6
Source File: GroupsResource.java    From bouncr with Eclipse Public License 1.0 5 votes vote down vote up
@Decision(HANDLE_OK)
public List<Group> handleOk(GroupSearchParams params, UserPermissionPrincipal principal, EntityManager em) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Group> query = cb.createQuery(Group.class);
    Root<Group> groupRoot = query.from(Group.class);
    query.distinct(true);
    query.orderBy(cb.asc(groupRoot.get("id")));

    List<ResourceField> embedEntities = some(params.getEmbed(), embed -> new ResourceFilter().parse(embed))
            .orElse(Collections.emptyList());
    EntityGraph<Group> groupGraph = em.createEntityGraph(Group.class);
    groupGraph.addAttributeNodes("name", "description");

    List<Predicate> predicates = new ArrayList<>();
    if (!principal.hasPermission("any_group:read")) {
        Join<User, Group> userJoin = groupRoot.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(groupRoot.get("name"), likeExpr, '_'));
            });
    if (!predicates.isEmpty()) {
        query.where(predicates.toArray(Predicate[]::new));
    }


    if (embedEntities.stream().anyMatch(r -> r.getName().equalsIgnoreCase("users"))) {
        groupGraph.addAttributeNodes("users");
        groupGraph.addSubgraph("users")
                .addAttributeNodes("account");
    }
    return em.createQuery(query)
            .setHint("javax.persistence.fetchgraph", groupGraph)
            .setFirstResult(params.getOffset())
            .setMaxResults(params.getLimit())
            .getResultList();
}
 
Example 7
Source File: GroupResource.java    From bouncr with Eclipse Public License 1.0 4 votes vote down vote up
@Decision(EXISTS)
public boolean exists(Parameters params,
                      UserPermissionPrincipal principal,
                      HttpRequest request,
                      RestContext context,
                      EntityManager em) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Group> query = cb.createQuery(Group.class);
    Root<Group> groupRoot = query.from(Group.class);

    List<Predicate> predicates = new ArrayList<>();
    predicates.add(cb.equal(groupRoot.get("name"), params.get("name")));
    if ((request.getRequestMethod().equalsIgnoreCase("GET") && !principal.hasPermission("any_group:read"))
            || (request.getRequestMethod().equalsIgnoreCase("PUT") && !principal.hasPermission("any_group:update"))
            || (request.getRequestMethod().equalsIgnoreCase("DELETE") && !principal.hasPermission("any_group:delete"))) {
        Join<Group, User> userRoot = groupRoot.join("users");
        predicates.add(cb.equal(userRoot.get("id"), principal.getId()));
    }

    if (!predicates.isEmpty()) {
        query.where(predicates.toArray(Predicate[]::new));
    }

    List<ResourceField> embedEntities = some(params.get("embed"), embed -> new ResourceFilter().parse(embed))
            .orElse(Collections.emptyList());
    EntityGraph<Group> groupGraph = em.createEntityGraph(Group.class);
    groupGraph.addAttributeNodes("name", "description");

    if (embedEntities.stream().anyMatch(r -> r.getName().equalsIgnoreCase("users"))) {
        groupGraph.addAttributeNodes("users");
        groupGraph.addSubgraph("users")
                .addAttributeNodes("account");
    }

    Group group = em.createQuery(query)
            .setHint("javax.persistence.fetchgraph", groupGraph)
            .getResultStream().findAny().orElse(null);
    if (group != null) {
        context.putValue(group);
    }
    return group != null;
}
 
Example 8
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 9
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;
}