javax.persistence.criteria.Subquery Java Examples

The following examples show how to use javax.persistence.criteria.Subquery. 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: ArticleSpecifications.java    From wallride with Apache License 2.0 10 votes vote down vote up
public static Specification<Article> draft(Article article) {
	return (root, query, cb) -> {
		List<Predicate> predicates = new ArrayList<>();
		predicates.add(cb.equal(root.get(Article_.drafted), article));

		Subquery<Long> subquery = query.subquery(Long.class);
		Root<Article> p = subquery.from(Article.class);
		subquery.select(cb.max(p.get(Article_.id))).where(cb.equal(p.get(Article_.drafted), article));

		predicates.add(cb.equal(root.get(Article_.id), subquery));
		return cb.and(predicates.toArray(new Predicate[0]));
	};
}
 
Example #2
Source File: PostServiceImpl.java    From halo with GNU General Public License v3.0 7 votes vote down vote up
/**
 * Build specification by post query.
 *
 * @param postQuery post query must not be null
 * @return a post specification
 */
@NonNull
private Specification<Post> buildSpecByQuery(@NonNull PostQuery postQuery) {
    Assert.notNull(postQuery, "Post query must not be null");

    return (Specification<Post>) (root, query, criteriaBuilder) -> {
        List<Predicate> predicates = new LinkedList<>();

        if (postQuery.getStatus() != null) {
            predicates.add(criteriaBuilder.equal(root.get("status"), postQuery.getStatus()));
        }

        if (postQuery.getCategoryId() != null) {
            Subquery<Post> postSubquery = query.subquery(Post.class);
            Root<PostCategory> postCategoryRoot = postSubquery.from(PostCategory.class);
            postSubquery.select(postCategoryRoot.get("postId"));
            postSubquery.where(
                criteriaBuilder.equal(root.get("id"), postCategoryRoot.get("postId")),
                criteriaBuilder.equal(postCategoryRoot.get("categoryId"),
                    postQuery.getCategoryId()));
            predicates.add(criteriaBuilder.exists(postSubquery));
        }

        if (postQuery.getKeyword() != null) {
            // Format like condition
            String likeCondition = String
                .format("%%%s%%", StringUtils.strip(postQuery.getKeyword()));

            // Build like predicate
            Predicate titleLike = criteriaBuilder.like(root.get("title"), likeCondition);
            Predicate originalContentLike = criteriaBuilder
                .like(root.get("originalContent"), likeCondition);

            predicates.add(criteriaBuilder.or(titleLike, originalContentLike));
        }

        return query.where(predicates.toArray(new Predicate[0])).getRestriction();
    };
}
 
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: RuleDAOJpa.java    From rice with Educational Community License v2.0 6 votes vote down vote up
@Override
public List<RuleBaseValues> search(String docTypeName, String ruleTemplateId, String ruleDescription, Collection<String> workgroupIds, String workflowId, Boolean delegateRule, Boolean activeInd, Map extensionValues, Collection actionRequestCodes) {
    CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
    CriteriaQuery<RuleBaseValues> cq = cb.createQuery(RuleBaseValues.class);
    Root<RuleBaseValues> root = cq.from(RuleBaseValues.class);
    List<javax.persistence.criteria.Predicate> predicates = getSearchCriteria(root,cq,docTypeName,
                    ruleTemplateId, ruleDescription, delegateRule, activeInd, extensionValues);
    Subquery<RuleResponsibilityBo> subquery = addResponsibilityCriteria(cq,workgroupIds, workflowId, actionRequestCodes,
                    (workflowId != null), ((workgroupIds != null) && !workgroupIds.isEmpty()));
    if (subquery != null){
        predicates.add(cb.in(root.get("id")).value(subquery));
    }
    javax.persistence.criteria.Predicate[] preds = predicates.toArray(new javax.persistence.criteria.Predicate[predicates.size()]);
    cq.where(preds);
    TypedQuery<RuleBaseValues> q = getEntityManager().createQuery(cq);

    return q.getResultList();
}
 
Example #5
Source File: EmployeeSearchServiceImpl.java    From tutorials with MIT License 6 votes vote down vote up
@Override
public List<DeptEmployee> searchByDepartmentQuery(String searchKey) {
    CriteriaQuery<DeptEmployee> criteriaQuery = createCriteriaQuery(DeptEmployee.class);
    Root<DeptEmployee> emp = criteriaQuery.from(DeptEmployee.class);

    Subquery<Department> subquery = criteriaQuery.subquery(Department.class);
    Root<Department> dept = subquery.from(Department.class);
    subquery.select(dept)
        .distinct(true)
        .where(criteriaBuilder.like(dept.get("name"), new StringBuffer("%").append(searchKey)
            .append("%")
            .toString()));

    criteriaQuery.select(emp)
        .where(criteriaBuilder.in(emp.get("department"))
            .value(subquery));

    TypedQuery<DeptEmployee> query = entityManager.createQuery(criteriaQuery);
    return query.getResultList();
}
 
Example #6
Source File: NativeJpaQueryTranslator.java    From rice with Educational Community License v2.0 6 votes vote down vote up
@Override
protected void addNotExistsSubquery(TranslationContext criteria, String subQueryType,
        org.kuali.rice.core.api.criteria.Predicate subQueryPredicate) {

    try {
        Class<?> subQueryBaseClass = Class.forName(subQueryType);
        Subquery<?> subquery = criteria.query.subquery(subQueryBaseClass);
        TranslationContext subQueryJpaPredicate = createCriteriaForSubQuery(subQueryBaseClass, criteria);

        // If a subQueryPredicate is passed, this is a Rice Predicate object and must be translated
        // into JPA - so we add it to the list this way.
        if (subQueryPredicate != null) {
            addPredicate(subQueryPredicate, subQueryJpaPredicate);
        }

        subquery.where(subQueryJpaPredicate.predicates.toArray(new Predicate[0]));
        criteria.addNotExistsSubquery(subquery);

    } catch (ClassNotFoundException e) {
            throw new IllegalArgumentException(subQueryType + " can not be resolved to a class for JPA");
    }
}
 
Example #7
Source File: BuildRecordPredicates.java    From pnc with Apache License 2.0 6 votes vote down vote up
/**
 * (related to NCL-5192, NCL-5351)
 *
 * When (re)building a temporary build: - if there are existing *successful* temporary builds having the same idRev,
 * ignore persistent builds - if there are no existing temporary builds having the same idRev, include also
 * persistent builds having the same idRev
 *
 * When (re)building a persistent build: - include only existing persistent builds having the same idRev
 *
 * @param idRev the revision of the build to (re)build
 * @param temporary if requested (re)build is temporary
 * @return Predicate that filters out builds according to description
 */
public static Predicate<BuildRecord> includeTemporary(IdRev idRev, boolean temporary) {
    return (root, query, cb) -> {
        if (temporary) {
            // Create subquery that counts number of temporary builds for the same BuildConfigurationAudited.idRev
            Subquery<Long> temporaryCount = query.subquery(Long.class);
            Root<BuildRecord> subRoot = temporaryCount.from(BuildRecord.class);
            temporaryCount.select(cb.count(subRoot.get(BuildRecord_.id)));
            temporaryCount.where(
                    cb.and(
                            cb.isTrue(subRoot.get(BuildRecord_.temporaryBuild)),
                            cb.equal(subRoot.get(BuildRecord_.status), BuildStatus.SUCCESS),
                            cb.equal(subRoot.get(BuildRecord_.buildConfigurationId), idRev.getId()),
                            cb.equal(subRoot.get(BuildRecord_.buildConfigurationRev), idRev.getRev())));

            // only false if build is persistent and there are temporaryBuilds present
            return cb
                    .or(cb.isTrue(root.get(BuildRecord_.temporaryBuild)), cb.lessThanOrEqualTo(temporaryCount, 0L));
        }
        return cb.isFalse(root.get(BuildRecord_.temporaryBuild));
    };
}
 
Example #8
Source File: NativeJpaQueryTranslator.java    From rice with Educational Community License v2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected void addExistsSubquery(TranslationContext criteria, String subQueryType,
		org.kuali.rice.core.api.criteria.Predicate subQueryPredicate) {
	try {
		Class<?> subQueryBaseClass = Class.forName(subQueryType);
		Subquery<?> subquery = criteria.query.subquery(subQueryBaseClass);
		TranslationContext subQueryJpaPredicate = createCriteriaForSubQuery(subQueryBaseClass, criteria);

		// If a subQueryPredicate is passed, this is a Rice Predicate object and must be translated
		// into JPA - so we add it to the list this way.
		if (subQueryPredicate != null) {
			addPredicate(subQueryPredicate, subQueryJpaPredicate);
		}

		subquery.where(subQueryJpaPredicate.predicates.toArray(new Predicate[0]));
		criteria.addExistsSubquery(subquery);
	} catch (ClassNotFoundException e) {
		throw new IllegalArgumentException(subQueryType + " can not be resolved to a class for JPA");
	}
}
 
Example #9
Source File: PageSpecifications.java    From wallride with Apache License 2.0 6 votes vote down vote up
public static Specification<Page> draft(Page page) {
	return (root, query, cb) -> {
		List<Predicate> predicates = new ArrayList<>();
		predicates.add(cb.equal(root.get(Page_.drafted), page));

		Subquery<Long> subquery = query.subquery(Long.class);
		Root<Page> p = subquery.from(Page.class);
		subquery.select(cb.max(p.get(Page_.id))).where(cb.equal(p.get(Page_.drafted), page));

		predicates.add(cb.equal(root.get(Page_.id), subquery));
		return cb.and(predicates.toArray(new Predicate[0]));
	};
}
 
Example #10
Source File: RuleDelegationDAOJpa.java    From rice with Educational Community License v2.0 5 votes vote down vote up
private Subquery<RuleResponsibilityBo> getResponsibilitySubQuery(CriteriaQuery<RuleBaseValues> query, Collection<String> kimGroupIds, String principalId, Boolean searchUser, Boolean searchUserInWorkgroups) {
    Collection<String> workgroupIdStrings = new ArrayList<String>();

    for (String workgroupId : kimGroupIds) {
        workgroupIdStrings.add(workgroupId.toString());
    }

    return getResponsibilitySubQuery(query, workgroupIdStrings,principalId,new ArrayList<String>(), searchUser, searchUserInWorkgroups);
}
 
Example #11
Source File: AbstractModelQuery.java    From elexis-3-core with Eclipse Public License 1.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public <S> ISubQuery<S> createSubQuery(Class<S> clazz, IModelService modelService){
	Class<? extends EntityWithId> subEntityClazz =
		(Class<? extends EntityWithId>) modelService.getEntityClass(clazz);
	Subquery<? extends EntityWithId> sq = criteriaQuery.subquery(subEntityClazz);
	return new SubQuery<S>(sq, subEntityClazz);
}
 
Example #12
Source File: ClusterPredicates.java    From genie with Apache License 2.0 5 votes vote down vote up
/**
 * Get the {@link Predicate} for the query which will find the clusters which match the given criterion.
 *
 * @param root      The {@link Root} of the query
 * @param cq        The {@link CriteriaQuery}
 * @param cb        The {@link CriteriaBuilder}
 * @param criterion The {@link Criterion} to match clusters against
 * @return A {@link Predicate} for this query
 */
public static Predicate findClustersMatchingCriterion(
    final Root<ClusterEntity> root,
    final CriteriaQuery<?> cq,
    final CriteriaBuilder cb,
    final Criterion criterion
) {
    final Subquery<Long> criterionSubquery = cq.subquery(Long.class);
    final Root<ClusterEntity> criterionSubqueryRoot = criterionSubquery.from(ClusterEntity.class);
    criterionSubquery.select(criterionSubqueryRoot.get(ClusterEntity_.id));
    criterionSubquery.where(
        PredicateUtils.createCriterionPredicate(
            criterionSubqueryRoot,
            criterionSubquery,
            cb,
            ClusterEntity_.uniqueId,
            ClusterEntity_.name,
            ClusterEntity_.version,
            ClusterEntity_.status,
            () -> criterionSubqueryRoot.join(ClusterEntity_.tags, JoinType.INNER),
            ClusterEntity_.id,
            criterion
        )
    );

    return root.get(ClusterEntity_.id).in(criterionSubquery);
}
 
Example #13
Source File: CommandPredicates.java    From genie with Apache License 2.0 5 votes vote down vote up
/**
 * Get the specification for the query which will find the commands which match the given criterion.
 *
 * @param root      The {@link Root} (from) for the query
 * @param cq        The {@link CriteriaQuery} instance
 * @param cb        The {@link CriteriaBuilder} instance
 * @param criterion The {@link Criterion} to match commands against
 * @return A {@link Predicate} for this query
 */
public static Predicate findCommandsMatchingCriterion(
    final Root<CommandEntity> root,
    final CriteriaQuery<?> cq,
    final CriteriaBuilder cb,
    final Criterion criterion
) {
    final Subquery<Long> criterionSubquery = cq.subquery(Long.class);
    final Root<CommandEntity> criterionSubqueryRoot = criterionSubquery.from(CommandEntity.class);
    criterionSubquery.select(criterionSubqueryRoot.get(CommandEntity_.id));
    criterionSubquery.where(
        cb.and(
            PredicateUtils.createCriterionPredicate(
                criterionSubqueryRoot,
                criterionSubquery,
                cb,
                CommandEntity_.uniqueId,
                CommandEntity_.name,
                CommandEntity_.version,
                CommandEntity_.status,
                () -> criterionSubqueryRoot.join(CommandEntity_.tags, JoinType.INNER),
                CommandEntity_.id,
                criterion
            ),
            cb.isNotEmpty(criterionSubqueryRoot.get(CommandEntity_.clusterCriteria))
        )
    );

    return root.get(CommandEntity_.id).in(criterionSubquery);
}
 
Example #14
Source File: RuleDelegationDAOJpa.java    From rice with Educational Community License v2.0 5 votes vote down vote up
/**
 * This overridden method ...
 *
 * @see org.kuali.rice.kew.rule.dao.RuleDelegationDAO#search(String, Long, String, java.util.Collection, String, String, Boolean, java.util.Map, java.util.Collection)
 */
public List<RuleDelegationBo> search(String parentRuleBaseVaueId, String parentResponsibilityId, String docTypeName, String ruleTemplateId,
        String ruleDescription, Collection<String> workgroupIds,
        String principalId, String delegationType, Boolean activeInd,
        Map extensionValues, Collection actionRequestCodes) {
    // TODO jjhanso - THIS METHOD NEEDS JAVADOCS
    CriteriaBuilder criteriaBuilder = getEntityManager().getCriteriaBuilder();
    CriteriaQuery<RuleDelegationBo> criteriaQuery = criteriaBuilder.createQuery(RuleDelegationBo.class);
    Root<RuleDelegationBo> root = criteriaQuery.from(RuleDelegationBo.class);
    List<javax.persistence.criteria.Predicate> predicates = new ArrayList<javax.persistence.criteria.Predicate>();
    if (StringUtils.isNotBlank(delegationType) && !delegationType.equals(KewApiConstants.DELEGATION_BOTH)) {
        predicates.add(criteriaBuilder.equal(root.get("delegationTypeCode"), delegationType));
    }
    if (StringUtils.isNotBlank(parentResponsibilityId) && StringUtils.isNumeric(parentResponsibilityId)) {
        predicates.add(criteriaBuilder.equal(root.get("responsibilityId"),parentResponsibilityId));
    }

    if (StringUtils.isNotBlank(parentRuleBaseVaueId) && StringUtils.isNumeric(parentRuleBaseVaueId)) {
        predicates.add(criteriaBuilder.in(root.get("responsibilityId")).value(getRuleResponsibilitySubQuery(new Long(parentRuleBaseVaueId),criteriaQuery)));
    }
    Subquery<RuleBaseValues> ruleBaseValuesSubQuery = getRuleBaseValuesSubQuery(docTypeName, ruleTemplateId, ruleDescription, workgroupIds,principalId, activeInd,extensionValues,actionRequestCodes,criteriaQuery);
    if(ruleBaseValuesSubQuery != null){
        predicates.add(criteriaBuilder.in(root.get("delegateRuleId")).value(ruleBaseValuesSubQuery));
    }
    criteriaQuery.distinct(true);
    TypedQuery<RuleDelegationBo> typedQuery = getEntityManager().createQuery(criteriaQuery);
    typedQuery.setMaxResults(KewApiConstants.DELEGATE_RULE_LOOKUP_MAX_ROWS_RETURNED);

    return typedQuery.getResultList();
}
 
Example #15
Source File: RuleDelegationDAOJpa.java    From rice with Educational Community License v2.0 5 votes vote down vote up
private List<javax.persistence.criteria.Predicate> getSearchCriteria(Root<RuleBaseValues> root,CriteriaQuery<RuleBaseValues> query,
        String docTypeName, String ruleTemplateId,
        String ruleDescription, Boolean activeInd, Map<String,String> extensionValues) {
    List<javax.persistence.criteria.Predicate> predicates = new ArrayList<javax.persistence.criteria.Predicate>();
    CriteriaBuilder criteribaBuilder = getEntityManager().getCriteriaBuilder();

    predicates.add(criteribaBuilder.equal(root.get("currentInd"),Boolean.TRUE));
    predicates.add(criteribaBuilder.equal(root.get("templateRuleInd"), Boolean.FALSE));
    if (activeInd != null) {
        predicates.add(criteribaBuilder.equal(root.get("active"),activeInd));
    }
    if (docTypeName != null) {
        predicates.add(criteribaBuilder.like(criteribaBuilder.upper(root.<String>get("docTypeName")), docTypeName.toUpperCase()));
    }
    if (ruleDescription != null && !ruleDescription.trim().equals("")) {
        predicates.add(criteribaBuilder.like(criteribaBuilder.upper(root.<String>get("description")),ruleDescription.toUpperCase()));
    }
    if (ruleTemplateId != null) {
        predicates.add(criteribaBuilder.equal(root.get("ruleTemplateId"),ruleTemplateId));
    }

    if (extensionValues != null && !extensionValues.isEmpty()) {
        for (Map.Entry<String,String> entry : extensionValues.entrySet()) {
            if (!StringUtils.isEmpty(entry.getValue())) {
                Subquery ruleExtSubQuery = query.subquery(RuleExtensionBo.class);
                Root<RuleExtensionBo> ruleExtRoot = ruleExtSubQuery.from(RuleExtensionBo.class);
                javax.persistence.criteria.Predicate predAnd = criteribaBuilder.and(
                        criteribaBuilder.equal(ruleExtRoot.get("extensionValues").get("key"),entry.getKey()),
                        criteribaBuilder.like(ruleExtRoot.get("extensionValues").<String>get("value"),
                                ("%" + (String) entry.getValue() + "%").toUpperCase()));
                ruleExtSubQuery.where(predAnd);
                ruleExtSubQuery.select(ruleExtRoot.get("ruleBaseValuesId"));

                predicates.add(criteribaBuilder.in(root.get("id")).value(ruleExtSubQuery));
            }
        }
    }
    return predicates;
}
 
Example #16
Source File: RuleDAOJpa.java    From rice with Educational Community License v2.0 5 votes vote down vote up
private Subquery<RuleResponsibilityBo> getRuleResponsibilitySubQuery(String ruleRespName,
                    CriteriaQuery<RuleBaseValues> query){
    CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
    Subquery<RuleResponsibilityBo> subquery = query.subquery(RuleResponsibilityBo.class);
    Root fromResp = subquery.from(RuleResponsibilityBo.class);
    subquery.where(cb.equal(fromResp.get("ruleResponsibilityName"),ruleRespName));
    subquery.select(fromResp.get("ruleBaseValuesId"));

    return subquery;
}
 
Example #17
Source File: RuleDelegationDAOJpa.java    From rice with Educational Community License v2.0 5 votes vote down vote up
/**
 * Method that returns a subquery that selects rule id from rule responsibility table based on certain criteria
 * @param ruleResponsibilityName is the responsibility name
 * @param query is he criteria query
 * @return a subquery that selects the rule id from rule responsibility table where responsibility name equals the rule responsibility name that is passed in as parameter to this method
 */
private Subquery<RuleResponsibilityBo> getResponsibilitySubQuery(String ruleResponsibilityName, CriteriaQuery<RuleBaseValues> query){
    CriteriaBuilder criteriaBuilder = getEntityManager().getCriteriaBuilder();
    Subquery<RuleResponsibilityBo> ruleResponsibilitySubquery = query.subquery(RuleResponsibilityBo.class);
    Root fromResp = ruleResponsibilitySubquery.from(RuleResponsibilityBo.class);
    ruleResponsibilitySubquery.where(criteriaBuilder.equal(fromResp.get("ruleResponsibilityName"),ruleResponsibilityName));
    ruleResponsibilitySubquery.select(fromResp.get("ruleBaseValuesId"));

    return ruleResponsibilitySubquery;
}
 
Example #18
Source File: RdbmsUtils.java    From modeldb with Apache License 2.0 5 votes vote down vote up
private static Predicate getPredicateFromSubquery(
    CriteriaBuilder builder,
    Root<?> entityRootPath,
    Operator operator,
    Subquery<String> subquery,
    String fieldName) {
  Expression<String> exp = entityRootPath.get(fieldName);
  if (operator.equals(Operator.NOT_CONTAIN) || operator.equals(Operator.NE)) {
    return builder.not(exp.in(subquery));
  } else {
    return exp.in(subquery);
  }
}
 
Example #19
Source File: RuleDelegationDAOJpa.java    From rice with Educational Community License v2.0 5 votes vote down vote up
/**
 * Method that selects the responsibility id from rule responsibility table where rule id is equal to the value that is passed as parameter to this method
 * @param ruleBaseValuesId is the rule id
 * @param query is the criteria query
 * @return a subquery
 */
private Subquery<RuleResponsibilityBo> getRuleResponsibilitySubQuery(Long ruleBaseValuesId, CriteriaQuery<RuleDelegationBo> query){
    CriteriaBuilder criteriaBuilder = getEntityManager().getCriteriaBuilder();
    Subquery<RuleResponsibilityBo> ruleResponsibilityBoSubquery = query.subquery(RuleResponsibilityBo.class);
    Root fromResp = ruleResponsibilityBoSubquery.from(RuleResponsibilityBo.class);
    ruleResponsibilityBoSubquery.where(criteriaBuilder.equal(fromResp.get("ruleBaseValuesId"),ruleBaseValuesId));
    ruleResponsibilityBoSubquery.select(fromResp.get("responsibilityId"));

    return ruleResponsibilityBoSubquery;
}
 
Example #20
Source File: RuleDAOJpa.java    From rice with Educational Community License v2.0 5 votes vote down vote up
private Subquery<RuleResponsibilityBo> addResponsibilityCriteria(CriteriaQuery<RuleBaseValues> query, Collection<String> kimGroupIds,
        String principalId, Boolean searchUser, Boolean searchUserInWorkgroups) {
    Collection<String> workgroupIdStrings = new ArrayList<String>();
    for (String workgroupId : kimGroupIds) {
        workgroupIdStrings.add(workgroupId.toString());
    }
    return addResponsibilityCriteria(query, workgroupIdStrings,principalId,new ArrayList<String>(),
                                    searchUser, searchUserInWorkgroups);
}
 
Example #21
Source File: AbstractModelQuery.java    From elexis-3-core with Eclipse Public License 1.0 5 votes vote down vote up
public SubQuery(Subquery<? extends EntityWithId> subQuery,
	Class<? extends EntityWithId> entityClazz){
	this.subQuery = subQuery;
	this.entityClazz = entityClazz;
	this.subRootQuery = subQuery.from(entityClazz);
	this.predicateGroups = new PredicateGroupStack(criteriaBuilder);
	this.predicateHandler =
		new PredicateHandler(predicateGroups, entityClazz, criteriaBuilder, subRootQuery);
	
	if (EntityWithDeleted.class.isAssignableFrom(entityClazz) && !includeDeleted) {
		and(ModelPackage.Literals.DELETEABLE__DELETED, COMPARATOR.NOT_EQUALS, true);
	}
}
 
Example #22
Source File: TestJpaDao.java    From jdal with Apache License 2.0 5 votes vote down vote up
@Test
@Transactional
public void testCopy() {
	EntityManager em = bookDao.getEntityManager();
	CriteriaBuilder cb = em.getCriteriaBuilder();
	CriteriaQuery<Book> criteria = cb.createQuery(Book.class);
	
	// Fetch join
	Root<Book> root = criteria.from(Book.class);
	Path<String> path = root.join("author").<String>get("name");
	root.fetch("author");
	criteria.select(root);
	
	// SubQuery
	Subquery<String> sq = criteria.subquery(String.class);
	Root<Author> author = sq.from(Author.class);
	sq.select(author.<String>get("name"));
	sq.where(cb.equal(author.<String>get("name"), "Rod"));
	
	criteria.where(cb.in(path).value(sq));
	
	CriteriaQuery<Book> copy = cb.createQuery(Book.class);
	JpaUtils.copyCriteria(criteria, copy);
	
	List<Book> copyBooks = em.createQuery(copy).getResultList();
	List<Book> books = em.createQuery(criteria).getResultList();
	assertEquals(books, copyBooks);
}
 
Example #23
Source File: RuleDelegationDAOJpa.java    From rice with Educational Community License v2.0 5 votes vote down vote up
/**
 * This overridden method ...
 *
 * @see org.kuali.rice.kew.rule.dao.RuleDelegationDAO#search(String, Long, Long, String, String, String, String, Boolean, java.util.Map, String)
 */
@Override
public List<RuleDelegationBo> search(String parentRuleBaseVaueId, String parentResponsibilityId, String docTypeName, String ruleId,
        String ruleTemplateId, String ruleDescription, String workgroupId,
        String principalId, String delegationType, Boolean activeInd,
        Map extensionValues, String workflowIdDirective) {
    // TODO jjhanso - THIS METHOD NEEDS JAVADOCS
    CriteriaBuilder criteriaBuilder = getEntityManager().getCriteriaBuilder();
    CriteriaQuery<RuleDelegationBo> criteriaQuery = criteriaBuilder.createQuery(RuleDelegationBo.class);
    Root<RuleDelegationBo> root = criteriaQuery.from(RuleDelegationBo.class);
    List<javax.persistence.criteria.Predicate> predicates = new ArrayList<javax.persistence.criteria.Predicate>();
    if (StringUtils.isNotBlank(delegationType) && !delegationType.equals(KewApiConstants.DELEGATION_BOTH)) {
        predicates.add(criteriaBuilder.equal(root.get("delegationTypeCode"), delegationType));
    }
    if (StringUtils.isNotBlank(parentResponsibilityId) && StringUtils.isNumeric(parentResponsibilityId)) {
        predicates.add(criteriaBuilder.equal(root.get("responsibilityId"),parentResponsibilityId));
    }

    if (StringUtils.isNotBlank(parentRuleBaseVaueId) && StringUtils.isNumeric(parentRuleBaseVaueId)) {
        predicates.add(criteriaBuilder.in(root.get("responsibilityId")).value(getRuleResponsibilitySubQuery(new Long(parentRuleBaseVaueId),criteriaQuery)));
    }
    Subquery<RuleBaseValues> ruleBaseValuesSubQuery = getRuleBaseValuesSubQuery(docTypeName, ruleId, ruleTemplateId, ruleDescription, workgroupId,principalId, activeInd,extensionValues, workflowIdDirective,criteriaQuery);
    if(ruleBaseValuesSubQuery != null){
        predicates.add(criteriaBuilder.in(root.get("delegateRuleId")).value(ruleBaseValuesSubQuery));
    }
    criteriaQuery.distinct(true);
    javax.persistence.criteria.Predicate[] preds = predicates.toArray(
            new javax.persistence.criteria.Predicate[predicates.size()]);
    criteriaQuery.where(preds);
    TypedQuery<RuleDelegationBo> typedQuery = getEntityManager().createQuery(criteriaQuery);
    typedQuery.setMaxResults(KewApiConstants.DELEGATE_RULE_LOOKUP_MAX_ROWS_RETURNED);

    return typedQuery.getResultList();
}
 
Example #24
Source File: PageSpecifications.java    From wallride with Apache License 2.0 5 votes vote down vote up
public static Specification<Page> path(Page page, boolean includeUnpublished) {
		return (root, query, cb) -> {
//			query.distinct(true);
			Root<Page> p1 = query.from(Page.class);
			Root<Page> p2 = root;
			Root<Page> p3 = query.from(Page.class);

			List<Predicate> predicates = new ArrayList<>();
			predicates.add(cb.equal(root.get(Page_.language), page.getLanguage()));
			if (!includeUnpublished) {
				predicates.add(cb.equal(root.get(Page_.status), Page.Status.PUBLISHED));
			}

			Subquery<Long> subquery = query.subquery(Long.class);
			Root<Page> p = subquery.from(Page.class);
			subquery.select(p.get(Page_.id)).where(
					cb.equal(p.get(Page_.language), page.getLanguage()),
					cb.isNull(p.get(Page_.parent)),
					cb.le(p.get(Page_.lft), page.getLft()),
					cb.ge(p.get(Page_.rgt), page.getRgt()));

			predicates.add(cb.equal(p1.get(Page_.id), subquery));
			predicates.add(cb.equal(p3.get(Page_.id), page.getId()));
			predicates.add(cb.between(p2.get(Page_.lft), p1.get(Page_.lft), p1.get(Page_.rgt)));
			predicates.add(cb.between(p3.get(Page_.lft), p2.get(Page_.lft), p2.get(Page_.rgt)));
			query.orderBy(cb.desc(cb.diff(p2.get(Page_.rgt), p2.get(Page_.lft))));
			return cb.and(predicates.toArray(new Predicate[0]));
		};
	}
 
Example #25
Source File: BuildRecordPredicates.java    From pnc with Apache License 2.0 5 votes vote down vote up
public static Predicate<BuildRecord> withoutAttribute(String key) {
    return (root, query, cb) -> {
        Subquery<String> subquery = query.subquery(String.class);
        Root<BuildRecordAttribute> subRoot = subquery.from(BuildRecordAttribute.class);
        subquery.select(subRoot.get(BuildRecordAttribute_.key));
        subquery.where(
                cb.and(
                        cb.equal(subRoot.get(BuildRecordAttribute_.key), key),
                        cb.equal(root.get(BuildRecord_.id), subRoot.get(BuildRecordAttribute_.buildRecord))));
        return query.where(cb.not(cb.exists(subquery))).getRestriction();
    };
}
 
Example #26
Source File: BuildConfigSetRecordPredicates.java    From pnc with Apache License 2.0 5 votes vote down vote up
public static Predicate<BuildConfigSetRecord> newestWithBuildConfigSetID(Integer buildConfigSetId) {
    return (root, query, cb) -> {
        Subquery<Integer> subQuery = cb.createQuery(Integer.class).subquery(Integer.class);
        Root<BuildConfigSetRecord> subRoot = subQuery.from(BuildConfigSetRecord.class);
        javax.persistence.criteria.Predicate subSelect = cb.equal(
                subRoot.get(BuildConfigSetRecord_.buildConfigurationSet).get(BuildConfigurationSet_.id),
                buildConfigSetId);

        subQuery.select(cb.max(subRoot.get(BuildConfigSetRecord_.id))).where(subSelect);
        return cb.equal(root.get(BuildConfigSetRecord_.id), cb.any(subQuery));
    };
}
 
Example #27
Source File: ResourceDao.java    From osiam with MIT License 5 votes vote down vote up
private <T extends ResourceEntity> long getTotalResults(Class<T> clazz, Subquery<Long> internalIdQuery) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Long> resourceQuery = cb.createQuery(Long.class);
    Root<T> resourceRoot = resourceQuery.from(clazz);

    resourceQuery.select(cb.count(resourceRoot)).where(
            cb.in(resourceRoot.get(ResourceEntity_.internalId)).value(internalIdQuery));

    return em.createQuery(resourceQuery).getSingleResult();
}
 
Example #28
Source File: RSQLUtility.java    From hawkbit with Eclipse Public License 1.0 5 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
private Predicate toNotExistsSubQueryPredicate(final String[] fieldNames, final A enumField,
        final Function<Expression<String>, Predicate> subQueryPredicateProvider) {
    final Class<?> javaType = root.getJavaType();
    final Subquery<?> subquery = query.subquery(javaType);
    final Root subqueryRoot = subquery.from(javaType);
    final Predicate equalPredicate = cb.equal(root.get(enumField.identifierFieldName()),
            subqueryRoot.get(enumField.identifierFieldName()));
    final Path innerFieldPath = getInnerFieldPath(subqueryRoot, fieldNames, enumField.isMap());
    final Expression<String> expressionToCompare = getExpressionToCompare(innerFieldPath, enumField);
    final Predicate subQueryPredicate = subQueryPredicateProvider.apply(expressionToCompare);
    subquery.select(subqueryRoot).where(cb.and(equalPredicate, subQueryPredicate));
    return cb.not(cb.exists(subquery));
}
 
Example #29
Source File: ContestSupervisorHibernateDao.java    From judgels with GNU General Public License v2.0 5 votes vote down vote up
static CustomPredicateFilter<ContestModel> hasSupervisor(String userJid) {
    return (cb, cq, root) -> {
        Subquery<ContestSupervisorModel> sq = cq.subquery(ContestSupervisorModel.class);
        Root<ContestSupervisorModel> subRoot = sq.from(ContestSupervisorModel.class);

        sq.where(
                cb.equal(subRoot.get(ContestSupervisorModel_.contestJid), root.get(ContestModel_.jid)),
                cb.equal(subRoot.get(ContestSupervisorModel_.userJid), userJid));
        sq.select(subRoot);

        return cb.exists(sq);
    };
}
 
Example #30
Source File: RdbmsUtils.java    From modeldb with Apache License 2.0 5 votes vote down vote up
private static Predicate getPredicateFromSubquery(
    CriteriaBuilder builder,
    Root<?> entityRootPath,
    Operator operator,
    Subquery<String> subquery) {
  return getPredicateFromSubquery(
      builder, entityRootPath, operator, subquery, ModelDBConstants.ID);
}