Java Code Examples for javax.persistence.criteria.Root#get()

The following examples show how to use javax.persistence.criteria.Root#get() . 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: ProductMilestoneProviderImpl.java    From pnc with Apache License 2.0 6 votes vote down vote up
private CriteriaQuery<Tuple> milestoneInfoQuery(CriteriaBuilder cb, Set<Integer> milestoneIds) {
    CriteriaQuery<Tuple> query = cb.createTupleQuery();

    Root<org.jboss.pnc.model.ProductMilestone> milestone = query.from(org.jboss.pnc.model.ProductMilestone.class);
    Root<ProductRelease> release = query.from(ProductRelease.class);
    Path<ProductVersion> version = milestone.get(ProductMilestone_.productVersion);
    Path<Product> product = version.get(ProductVersion_.product);
    query.multiselect(
            product.get(Product_.id),
            product.get(Product_.name),
            version.get(ProductVersion_.id),
            version.get(ProductVersion_.version),
            milestone.get(ProductMilestone_.id),
            milestone.get(ProductMilestone_.version),
            milestone.get(ProductMilestone_.endDate),
            release.get(ProductRelease_.id),
            release.get(ProductRelease_.version),
            release.get(ProductRelease_.releaseDate));
    query.where(
            cb.and(cb.equal(release.get(ProductRelease_.productMilestone), milestone)),
            milestone.get(ProductMilestone_.id).in(milestoneIds));
    query.orderBy(cb.desc(milestone.get(ProductMilestone_.endDate)), cb.desc(milestone.get(ProductMilestone_.id)));
    return query;
}
 
Example 2
Source File: SecurityRoleDaoImpl.java    From herd with Apache License 2.0 6 votes vote down vote up
@Override
@Cacheable(DaoSpringModuleConfig.HERD_CACHE_NAME)
public List<SecurityRoleEntity> getAllSecurityRoles()
{
    // Create the criteria builder and the criteria.
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<SecurityRoleEntity> criteria = builder.createQuery(SecurityRoleEntity.class);

    // The criteria root is the security role
    Root<SecurityRoleEntity> securityRoleEntity = criteria.from(SecurityRoleEntity.class);

    // Create select query
    criteria.select(securityRoleEntity);

    // Get the role code column.
    Path<String> roleCodeColumn = securityRoleEntity.get(SecurityRoleEntity_.code);

    // Set the order by clause
    criteria.orderBy(builder.asc(roleCodeColumn));

    // run the query to get the list of security role entities and return them
    return entityManager.createQuery(criteria).getResultList();
}
 
Example 3
Source File: SecurityFunctionDaoImpl.java    From herd with Apache License 2.0 6 votes vote down vote up
@Override
@Cacheable(DaoSpringModuleConfig.HERD_CACHE_NAME)
public List<String> getUnrestrictedSecurityFunctions()
{
    // Create the criteria builder and the criteria.
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<String> criteria = builder.createQuery(String.class);

    // The criteria root is the security function.
    Root<SecurityFunctionEntity> securityFunctionEntityRoot = criteria.from(SecurityFunctionEntity.class);

    // Build a subquery to eliminate security functions that are mapped to security roles.
    Subquery<SecurityFunctionEntity> subquery = criteria.subquery(SecurityFunctionEntity.class);
    Root<SecurityRoleFunctionEntity> subSecurityRoleFunctionEntityRoot = subquery.from(SecurityRoleFunctionEntity.class);
    subquery.select(subSecurityRoleFunctionEntityRoot.get(SecurityRoleFunctionEntity_.securityFunction))
        .where(builder.equal(subSecurityRoleFunctionEntityRoot.get(SecurityRoleFunctionEntity_.securityFunction), securityFunctionEntityRoot));

    // Get the security function code column.
    Path<String> functionCodeColumn = securityFunctionEntityRoot.get(SecurityFunctionEntity_.code);

    // Add the clauses for the query.
    criteria.select(functionCodeColumn).where(builder.not(builder.exists(subquery))).orderBy(builder.asc(functionCodeColumn));

    // Run the query to get a list of unrestricted security functions.
    return entityManager.createQuery(criteria).getResultList();
}
 
Example 4
Source File: V2Count.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
private List<NameValueCountPair> groupByProcess(Business business, Predicate predicate) throws Exception {
	EntityManager em = business.entityManagerContainer().get(Read.class);
	CriteriaBuilder cb = em.getCriteriaBuilder();
	CriteriaQuery<Tuple> cq = cb.createQuery(Tuple.class);
	Root<Read> root = cq.from(Read.class);
	Path<String> pathProcess = root.get(Read_.process);
	Path<String> pathProcessName = root.get(Read_.processName);
	cq.multiselect(pathProcess, pathProcessName, cb.count(root)).where(predicate).groupBy(pathProcess);
	List<Tuple> os = em.createQuery(cq).getResultList();
	List<NameValueCountPair> list = new ArrayList<>();
	NameValueCountPair pair = null;
	for (Tuple o : os) {
		pair = new NameValueCountPair();
		pair.setName(o.get(pathProcessName));
		pair.setValue(o.get(pathProcess));
		pair.setCount(o.get(2, Long.class));
		list.add(pair);
	}
	return list.stream().sorted(Comparator.comparing(NameValueCountPair::getCount).reversed())
			.collect(Collectors.toList());
}
 
Example 5
Source File: V2Count.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
private List<NameValueCountPair> groupByProcess(Business business, Predicate predicate) throws Exception {
	EntityManager em = business.entityManagerContainer().get(Review.class);
	CriteriaBuilder cb = em.getCriteriaBuilder();
	CriteriaQuery<Tuple> cq = cb.createQuery(Tuple.class);
	Root<Review> root = cq.from(Review.class);
	Path<String> pathProcess = root.get(Review_.process);
	Path<String> pathProcessName = root.get(Review_.processName);
	cq.multiselect(pathProcess, pathProcessName, cb.count(root)).where(predicate).groupBy(pathProcess);
	List<Tuple> os = em.createQuery(cq).getResultList();
	List<NameValueCountPair> list = new ArrayList<>();
	NameValueCountPair pair = null;
	for (Tuple o : os) {
		pair = new NameValueCountPair();
		pair.setName(o.get(pathProcessName));
		pair.setValue(o.get(pathProcess));
		pair.setCount(o.get(2, Long.class));
		list.add(pair);
	}
	return list.stream().sorted(Comparator.comparing(NameValueCountPair::getCount).reversed())
			.collect(Collectors.toList());
}
 
Example 6
Source File: V2Count.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
private List<NameValueCountPair> groupByCreatorUnit(Business business, Predicate predicate) throws Exception {
	EntityManager em = business.entityManagerContainer().get(Task.class);
	CriteriaBuilder cb = em.getCriteriaBuilder();
	CriteriaQuery<Tuple> cq = cb.createQuery(Tuple.class);
	Root<Task> root = cq.from(Task.class);
	Path<String> pathCreatorUnit = root.get(Task_.creatorUnit);
	cq.multiselect(pathCreatorUnit, cb.count(root)).where(predicate).groupBy(pathCreatorUnit);
	List<Tuple> os = em.createQuery(cq).getResultList();
	List<NameValueCountPair> list = new ArrayList<>();
	NameValueCountPair pair = null;
	for (Tuple o : os) {
		pair = new NameValueCountPair();
		pair.setName(o.get(pathCreatorUnit));
		pair.setValue(o.get(pathCreatorUnit));
		pair.setCount(o.get(1, Long.class));
		list.add(pair);
	}
	return list.stream().sorted(Comparator.comparing(NameValueCountPair::getCount).reversed())
			.collect(Collectors.toList());
}
 
Example 7
Source File: FixedBetweenCriteria.java    From onedev with MIT License 5 votes vote down vote up
@Override
public Predicate getPredicate(Root<Issue> root, CriteriaBuilder builder) {
	Set<Long> fixedIssueNumbers = new HashSet<>();
	
	Repository repository = project.getRepository();
	ObjectId mergeBaseId = GitUtils.getMergeBase(repository, firstCommitId, secondCommitId);
	if (mergeBaseId != null) {
		try (RevWalk revWalk = new RevWalk(repository)) {
			revWalk.markStart(revWalk.parseCommit(secondCommitId));
			revWalk.markStart(revWalk.parseCommit(firstCommitId));
			revWalk.markUninteresting(revWalk.parseCommit(mergeBaseId));

			RevCommit commit;
			while ((commit = revWalk.next()) != null) 
				fixedIssueNumbers.addAll(IssueUtils.parseFixedIssueNumbers(commit.getFullMessage()));
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	Predicate issuePredicate;
	Path<Long> attribute = root.get(Issue.PROP_NUMBER);		
	if (fixedIssueNumbers.size() > IN_CLAUSE_LIMIT) {
		Collection<Long> allIssueNumbers = OneDev.getInstance(IssueManager.class).getIssueNumbers(project.getId());
		issuePredicate = inManyValues(builder, attribute, fixedIssueNumbers, allIssueNumbers);
	} else if (!fixedIssueNumbers.isEmpty()) {
		issuePredicate = root.get(Issue.PROP_NUMBER).in(fixedIssueNumbers);
	} else {
		issuePredicate = builder.disjunction();
	}
	return builder.and(
			builder.equal(root.get(Issue.PROP_PROJECT), project), 
			issuePredicate);
}
 
Example 8
Source File: ReplyCountCriteria.java    From onedev with MIT License 5 votes vote down vote up
@Override
public Predicate getPredicate(Root<CodeComment> root, CriteriaBuilder builder) {
	Path<Integer> attribute = root.get(CodeComment.PROP_REPLY_COUNT);
	if (operator == CodeCommentQueryLexer.Is)
		return builder.equal(attribute, value);
	else if (operator == CodeCommentQueryLexer.IsLessThan)
		return builder.lessThan(attribute, value);
	else
		return builder.greaterThan(attribute, value);
}
 
Example 9
Source File: MoviesBean.java    From tomee with Apache License 2.0 5 votes vote down vote up
public List<Movie> findRange(String field, String searchTerm, int firstResult, int maxResults) {
    CriteriaBuilder qb = entityManager.getCriteriaBuilder();
    CriteriaQuery<Movie> cq = qb.createQuery(Movie.class);
    Root<Movie> root = cq.from(Movie.class);
    EntityType<Movie> type = entityManager.getMetamodel().entity(Movie.class);

    Path<String> path = root.get(type.getDeclaredSingularAttribute(field, String.class));
    Predicate condition = qb.like(path, "%" + searchTerm + "%");

    cq.where(condition);
    TypedQuery<Movie> q = entityManager.createQuery(cq);
    q.setMaxResults(maxResults);
    q.setFirstResult(firstResult);
    return q.getResultList();
}
 
Example 10
Source File: CommentCountCriteria.java    From onedev with MIT License 5 votes vote down vote up
@Override
public Predicate getPredicate(Root<Issue> root, CriteriaBuilder builder) {
	Path<Integer> attribute = root.get(Issue.PROP_COMMENT_COUNT);
	if (operator == IssueQueryLexer.Is)
		return builder.equal(attribute, value);
	else if (operator == IssueQueryLexer.IsGreaterThan)
		return builder.greaterThan(attribute, value);
	else
		return builder.lessThan(attribute, value);
}
 
Example 11
Source File: CiServiceImpl.java    From we-cmdb with Apache License 2.0 5 votes vote down vote up
@Override
public List<CiKeyPair> retrieveKeyPairs(int ciTypeId) {
    DynamicEntityMeta entityMeta = getDynamicEntityMetaMap().get(ciTypeId);
    PriorityEntityManager priEntityManager = getEntityManager();
    EntityManager entityManager = priEntityManager.getEntityManager();
    List<CiKeyPair> ciKeyPairs = new LinkedList<>();
    try {
        CriteriaBuilder cb = entityManager.getCriteriaBuilder();
        CriteriaQuery query = cb.createQuery();
        Root root = query.from(entityMeta.getEntityClazz());
        Path guid = root.get(CmdbConstants.DEFAULT_FIELD_GUID);
        Path keyName = root.get(CmdbConstants.DEFAULT_FIELD_KEY_NAME);
        query.multiselect(guid,keyName).distinct(true);
        TypedQuery guidQuery =  entityManager.createQuery(query);
        List results = guidQuery.getResultList();
        ciKeyPairs = Lists.transform(results, (item) -> {
        	Object[] row = (Object[]) item;
        	CiKeyPair ciKeyPair = new CiKeyPair(String.valueOf(row[0]),String.valueOf(row[1]));
        	return ciKeyPair;
        });
        return ciKeyPairs;
    }
    catch(Exception ex) {
        throw new ServiceException(String.format("Failed to query guids for CI type [%d]", ciTypeId),ex);
    }finally {
        priEntityManager.close();
    }
}
 
Example 12
Source File: CommentCountCriteria.java    From onedev with MIT License 5 votes vote down vote up
@Override
public Predicate getPredicate(Root<PullRequest> root, CriteriaBuilder builder) {
	Path<Long> attribute = root.get(PullRequest.PROP_COMMENT_COUNT);
	if (operator == PullRequestQueryLexer.Is)
		return builder.equal(attribute, value);
	else if (operator == PullRequestQueryLexer.IsGreaterThan)
		return builder.greaterThan(attribute, value);
	else
		return builder.lessThan(attribute, value);
}
 
Example 13
Source File: MoviesBean.java    From microservice-with-jwt-and-microprofile with Apache License 2.0 5 votes vote down vote up
public int count(String field, String searchTerm) {
    CriteriaBuilder qb = entityManager.getCriteriaBuilder();
    CriteriaQuery<Long> cq = qb.createQuery(Long.class);
    Root<Movie> root = cq.from(Movie.class);
    EntityType<Movie> type = entityManager.getMetamodel().entity(Movie.class);
    cq.select(qb.count(root));
    if (field != null && searchTerm != null && !"".equals(field.trim()) && !"".equals(searchTerm.trim())) {
        Path<String> path = root.get(type.getDeclaredSingularAttribute(field.trim(), String.class));
        Predicate condition = qb.like(path, "%" + searchTerm.trim() + "%");
        cq.where(condition);
    }
    return entityManager.createQuery(cq).getSingleResult().intValue();
}
 
Example 14
Source File: FinishDateCriteria.java    From onedev with MIT License 5 votes vote down vote up
@Override
public Predicate getPredicate(Root<Build> root, CriteriaBuilder builder) {
	Path<Date> attribute = root.get(Build.PROP_FINISH_DATE);
	if (operator == BuildQueryLexer.IsBefore)
		return builder.lessThan(attribute, date);
	else
		return builder.greaterThan(attribute, date);
}
 
Example 15
Source File: StorageDaoImpl.java    From herd with Apache License 2.0 5 votes vote down vote up
@Override
public List<StorageKey> getAllStorage()
{
    // Create the criteria builder and a tuple style criteria query.
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<String> criteria = builder.createQuery(String.class);

    // The criteria root is the storage.
    Root<StorageEntity> storageEntity = criteria.from(StorageEntity.class);

    // Get the columns.
    Path<String> storageNameColumn = storageEntity.get(StorageEntity_.name);

    // Add the select clause.
    criteria.select(storageNameColumn);

    // Add the order by clause.
    criteria.orderBy(builder.asc(storageNameColumn));

    // Run the query to get a list of storage names back.
    List<String> storageNames = entityManager.createQuery(criteria).getResultList();

    // Populate the "keys" objects from the returned storage names.
    List<StorageKey> storageKeys = new ArrayList<>();
    for (String storageName : storageNames)
    {
        storageKeys.add(new StorageKey(storageName));
    }

    return storageKeys;
}
 
Example 16
Source File: TagDaoImpl.java    From herd with Apache License 2.0 5 votes vote down vote up
@Override
public List<TagEntity> getTagsByTagTypeEntityAndParentTagCode(TagTypeEntity tagTypeEntity, String parentTagCode, Boolean isParentTagNull)
{
    // Create the criteria builder and the criteria.
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<TagEntity> criteria = builder.createQuery(TagEntity.class);

    // The criteria root is the tag entity.
    Root<TagEntity> tagEntityRoot = criteria.from(TagEntity.class);

    // Get the columns.
    Path<String> displayNameColumn = tagEntityRoot.get(TagEntity_.displayName);

    // Create the standard restrictions (i.e. the standard where clauses).
    List<Predicate> predicates = new ArrayList<>();
    predicates.add(builder.equal(tagEntityRoot.get(TagEntity_.tagType), tagTypeEntity));

    if (StringUtils.isNotBlank(parentTagCode))
    {
        // Return all tags that are immediate children of the specified parent tag.
        predicates.add(builder.equal(builder.upper(tagEntityRoot.get(TagEntity_.parentTagEntity).get(TagEntity_.tagCode)), parentTagCode.toUpperCase()));
    }
    else if (BooleanUtils.isTrue(isParentTagNull))
    {
        // The flag is non-null and true, return all tags with no parents, i.e. root tags.
        predicates.add(builder.isNull(tagEntityRoot.get(TagEntity_.parentTagEntity)));
    }
    else if (BooleanUtils.isFalse(isParentTagNull))
    {
        // The flag is non-null and false, return all tags with parents.
        predicates.add(builder.isNotNull(tagEntityRoot.get(TagEntity_.parentTagEntity)));
    }

    // Add all clauses to the query.
    criteria.select(tagEntityRoot).where(builder.and(predicates.toArray(new Predicate[predicates.size()]))).orderBy(builder.asc(displayNameColumn));

    // Run the query to get the results.
    return entityManager.createQuery(criteria).getResultList();
}
 
Example 17
Source File: StorageUnitNotificationRegistrationDaoImpl.java    From herd with Apache License 2.0 5 votes vote down vote up
@Override
public List<NotificationRegistrationKey> getStorageUnitNotificationRegistrationKeysByNamespace(String namespace)
{
    // Create the criteria builder and a tuple style criteria query.
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Tuple> criteria = builder.createTupleQuery();

    // The criteria root is the storage unit notification registration.
    Root<StorageUnitNotificationRegistrationEntity> businessObjectDataNotificationEntityRoot =
        criteria.from(StorageUnitNotificationRegistrationEntity.class);

    // Join to the other tables we can filter on.
    Join<StorageUnitNotificationRegistrationEntity, NamespaceEntity> namespaceEntityJoin =
        businessObjectDataNotificationEntityRoot.join(StorageUnitNotificationRegistrationEntity_.namespace);

    // Get the columns.
    Path<String> notificationRegistrationNamespaceColumn = namespaceEntityJoin.get(NamespaceEntity_.code);
    Path<String> notificationRegistrationNameColumn = businessObjectDataNotificationEntityRoot.get(StorageUnitNotificationRegistrationEntity_.name);

    // Create the standard restrictions (i.e. the standard where clauses).
    Predicate queryRestriction = builder.equal(builder.upper(namespaceEntityJoin.get(NamespaceEntity_.code)), namespace.toUpperCase());

    // Add the select clause.
    criteria.multiselect(notificationRegistrationNamespaceColumn, notificationRegistrationNameColumn);

    // Add the where clause.
    criteria.where(queryRestriction);

    // Add the order by clause.
    criteria.orderBy(builder.asc(notificationRegistrationNameColumn));

    // Run the query to get a list of tuples back.
    List<Tuple> tuples = entityManager.createQuery(criteria).getResultList();

    // Populate the list of keys from the returned tuples.
    return getNotificationRegistrationKeys(tuples, notificationRegistrationNamespaceColumn, notificationRegistrationNameColumn);
}
 
Example 18
Source File: FailedCriteria.java    From onedev with MIT License 4 votes vote down vote up
@Override
public Predicate getPredicate(Root<Build> root, CriteriaBuilder builder) {
	Path<?> attribute = root.get(Build.PROP_STATUS);
	return builder.equal(attribute, Build.Status.FAILED);
}
 
Example 19
Source File: AbstractJpaStorage.java    From apiman with Apache License 2.0 4 votes vote down vote up
/**
 * Applies the criteria found in the {@link SearchCriteriaBean} to the JPA query.
 * @param criteria
 * @param builder
 * @param query
 * @param from
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
protected <T> void applySearchCriteriaToQuery(SearchCriteriaBean criteria, CriteriaBuilder builder,
        CriteriaQuery<?> query, Root<T> from, boolean countOnly) {

    List<SearchCriteriaFilterBean> filters = criteria.getFilters();
    if (filters != null && !filters.isEmpty()) {
        List<Predicate> predicates = new ArrayList<>();
        for (SearchCriteriaFilterBean filter : filters) {
            if (filter.getOperator() == SearchCriteriaFilterOperator.eq) {
                Path<Object> path = from.get(filter.getName());
                Class<?> pathc = path.getJavaType();
                if (pathc.isAssignableFrom(String.class)) {
                    predicates.add(builder.equal(path, filter.getValue()));
                } else if (pathc.isEnum()) {
                    predicates.add(builder.equal(path, Enum.valueOf((Class)pathc, filter.getValue())));
                }
            } else if (filter.getOperator() == SearchCriteriaFilterOperator.bool_eq) {
                predicates.add(builder.equal(from.<Boolean>get(filter.getName()), Boolean.valueOf(filter.getValue())));
            } else if (filter.getOperator() == SearchCriteriaFilterOperator.gt) {
                predicates.add(builder.greaterThan(from.<Long>get(filter.getName()), new Long(filter.getValue())));
            } else if (filter.getOperator() == SearchCriteriaFilterOperator.gte) {
                predicates.add(builder.greaterThanOrEqualTo(from.<Long>get(filter.getName()), new Long(filter.getValue())));
            } else if (filter.getOperator() == SearchCriteriaFilterOperator.lt) {
                predicates.add(builder.lessThan(from.<Long>get(filter.getName()), new Long(filter.getValue())));
            } else if (filter.getOperator() == SearchCriteriaFilterOperator.lte) {
                predicates.add(builder.lessThanOrEqualTo(from.<Long>get(filter.getName()), new Long(filter.getValue())));
            } else if (filter.getOperator() == SearchCriteriaFilterOperator.neq) {
                predicates.add(builder.notEqual(from.get(filter.getName()), filter.getValue()));
            } else if (filter.getOperator() == SearchCriteriaFilterOperator.like) {
                predicates.add(builder.like(builder.upper(from.<String>get(filter.getName())), filter.getValue().toUpperCase().replace('*', '%')));
            }
        }
        query.where(predicates.toArray(new Predicate[predicates.size()]));
    }
    OrderByBean orderBy = criteria.getOrderBy();
    if (orderBy != null && !countOnly) {
        if (orderBy.isAscending()) {
            query.orderBy(builder.asc(from.get(orderBy.getName())));
        } else {
            query.orderBy(builder.desc(from.get(orderBy.getName())));
        }
    }
}
 
Example 20
Source File: GenericTable.java    From HA-DB with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
protected Path<? extends Number> getAttributeName(Root<E> root, String attributeName) {
	return root.get(attributeName);
}