下面列出了javax.persistence.EntityManager#createEntityGraph ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@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.");
}
@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);
}
@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;
}
@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;
}
@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();
}
@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;
}
@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();
}
@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;
}