Example usage for javax.persistence.criteria CriteriaBuilder and

List of usage examples for javax.persistence.criteria CriteriaBuilder and

Introduction

In this page you can find the example usage for javax.persistence.criteria CriteriaBuilder and.

Prototype

Predicate and(Expression<Boolean> x, Expression<Boolean> y);

Source Link

Document

Create a conjunction of the given boolean expressions.

Usage

From source file:org.exoplatform.social.addons.storage.dao.jpa.query.RelationshipQueryBuilder.java

private Predicate buildPredicateFilter(CriteriaBuilder cb, Join<Connection, Profile> receiver,
        Root<Connection> connection) {
    Predicate predicate = null;/* w ww. j  a  va  2  s  .  c  o  m*/
    // owner
    if (this.owner != null) {
        predicate = cb.equal(connection.get(Connection_.senderId), owner.getId());
    }
    // status
    if (this.status != null) {
        predicate = cb.and(predicate, cb.equal(connection.get(Connection_.status), this.status));
    }

    Predicate pFilter = null;
    if (profileFilter != null) {
        String inputName = addPercentToStringInput(profileFilter.getName()).replace(ASTERISK_STR, SPACE_STR);
        String position = addPercentToStringInput(StringEscapeUtils.escapeHtml(profileFilter.getPosition()));
        String skills = addPercentToStringInput(StringEscapeUtils.escapeHtml(profileFilter.getSkills()));
        String company = addPercentToStringInput(StringEscapeUtils.escapeHtml(profileFilter.getCompany()));
        //
        if (!inputName.isEmpty()) {
            Predicate pName = cb.like(receiver.get(Profile_.fullName), inputName);
            pName = cb.or(pName, cb.like(receiver.get(Profile_.firstName), inputName));
            pFilter = cb.or(pName, cb.like(receiver.get(Profile_.lastName), inputName));
        }
        //
        if (!position.isEmpty()) {
            pFilter = appendPredicate(cb, pFilter, cb.like(receiver.get(Profile_.positions), position));
        }
        //
        if (!skills.isEmpty()) {
            pFilter = appendPredicate(cb, pFilter, cb.like(receiver.get(Profile_.skills), skills));
        }
        if (!company.isEmpty()) {
            pFilter = appendPredicate(cb, pFilter, cb.like(receiver.get(Profile_.organizations), company));
        }

        String all = profileFilter.getAll();
        if (all != null && !all.trim().isEmpty()) {
            all = escapeSpecialCharacter(all.trim()).toLowerCase();
            Predicate pAll = cb.like(receiver.get(Profile_.fullName), all);
            pAll = cb.or(pAll, cb.like(receiver.get(Profile_.firstName), all));
            pAll = cb.or(pAll, cb.like(receiver.get(Profile_.lastName), all));
            pAll = cb.or(pAll, cb.like(receiver.get(Profile_.skills), all));
            pAll = cb.or(pAll, cb.like(receiver.get(Profile_.positions), all));
            pAll = cb.or(pAll, cb.like(receiver.get(Profile_.organizations), all));
            pAll = cb.or(pAll, cb.like(receiver.get(Profile_.jobsDescription), all));
            //
            pFilter = appendPredicate(cb, pFilter, pAll);
        }
    }
    //
    return appendPredicate(cb, predicate, pFilter);
}

From source file:org.exoplatform.social.addons.storage.dao.jpa.query.RelationshipQueryBuilder.java

private Predicate appendPredicate(CriteriaBuilder cb, Predicate pSource, Predicate input) {
    if (pSource != null) {
        if (input != null) {
            return cb.and(pSource, input);
        }/*from   w  w w.  j  a va  2 s. com*/
        return pSource;
    } else {
        return input;
    }
}

From source file:org.fao.geonet.repository.HarvesterSettingRepositoryOverridesImpl.java

@Override
public List<HarvesterSetting> findChildrenByName(int parentid, String name) {
    CriteriaBuilder criteriaBuilder = _entityManager.getCriteriaBuilder();
    CriteriaQuery<HarvesterSetting> query = criteriaBuilder.createQuery(HarvesterSetting.class);

    Root<HarvesterSetting> root = query.from(HarvesterSetting.class);
    Predicate equalParentId = criteriaBuilder.equal(root.get(HarvesterSetting_.parent), parentid);
    Predicate equalName = criteriaBuilder.equal(root.get(HarvesterSetting_.name), name);
    query.where(criteriaBuilder.and(equalParentId, equalName));

    return _entityManager.createQuery(query).getResultList();
}

From source file:org.finra.dm.dao.impl.DmDaoImpl.java

/**
 * {@inheritDoc}/*from   w ww  .  j  a va2s  .c o m*/
 */
@Override
public BusinessObjectDefinitionEntity getBusinessObjectDefinitionByKey(
        BusinessObjectDefinitionKey businessObjectDefinitionKey) {
    // Create the criteria builder and the criteria.
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<BusinessObjectDefinitionEntity> criteria = builder
            .createQuery(BusinessObjectDefinitionEntity.class);

    // The criteria root is the business object definition.
    Root<BusinessObjectDefinitionEntity> businessObjectDefinitionEntity = criteria
            .from(BusinessObjectDefinitionEntity.class);

    // Join to the other tables we can filter on.
    Join<BusinessObjectDefinitionEntity, NamespaceEntity> namespaceEntity = businessObjectDefinitionEntity
            .join(BusinessObjectDefinitionEntity_.namespace);

    // Create the standard restrictions (i.e. the standard where clauses).
    Predicate queryRestriction = builder.equal(builder.upper(namespaceEntity.get(NamespaceEntity_.code)),
            businessObjectDefinitionKey.getNamespace().toUpperCase());
    queryRestriction = builder.and(queryRestriction,
            builder.equal(
                    builder.upper(businessObjectDefinitionEntity.get(BusinessObjectDefinitionEntity_.name)),
                    businessObjectDefinitionKey.getBusinessObjectDefinitionName().toUpperCase()));

    criteria.select(businessObjectDefinitionEntity).where(queryRestriction);

    return executeSingleResultQuery(criteria, String.format(
            "Found more than one business object definition with parameters {namespace=\"%s\", businessObjectDefinitionName=\"%s\"}.",
            businessObjectDefinitionKey.getNamespace(),
            businessObjectDefinitionKey.getBusinessObjectDefinitionName()));
}

From source file:org.finra.dm.dao.impl.DmDaoImpl.java

/**
 * {@inheritDoc}/*from  w  ww .  ja va  2 s  . c  o  m*/
 */
@Override
public BusinessObjectDefinitionEntity getLegacyBusinessObjectDefinitionByName(
        String businessObjectDefinitionName) {
    // Create the criteria builder and the criteria.
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<BusinessObjectDefinitionEntity> criteria = builder
            .createQuery(BusinessObjectDefinitionEntity.class);

    // The criteria root is the business object definition.
    Root<BusinessObjectDefinitionEntity> businessObjectDefinitionEntity = criteria
            .from(BusinessObjectDefinitionEntity.class);

    // Create the standard restrictions (i.e. the standard where clauses).
    Predicate queryRestriction = builder.equal(
            builder.upper(businessObjectDefinitionEntity.get(BusinessObjectDefinitionEntity_.name)),
            businessObjectDefinitionName.toUpperCase());
    queryRestriction = builder.and(queryRestriction,
            builder.isTrue(businessObjectDefinitionEntity.get(BusinessObjectDefinitionEntity_.legacy)));

    criteria.select(businessObjectDefinitionEntity).where(queryRestriction);

    return executeSingleResultQuery(criteria, String.format(
            "Found more than one business object definition with parameters {businessObjectDefinitionName=\"%s\", legacy=\"Y\"}.",
            businessObjectDefinitionName));
}

From source file:org.finra.dm.dao.impl.DmDaoImpl.java

/**
 * {@inheritDoc}/* www .j a v  a  2  s . co m*/
 */
@Override
public BusinessObjectFormatEntity getBusinessObjectFormatByAltKey(
        BusinessObjectFormatKey businessObjectFormatKey) {
    // Create the criteria builder and the criteria.
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<BusinessObjectFormatEntity> criteria = builder.createQuery(BusinessObjectFormatEntity.class);

    // The criteria root is the business object format.
    Root<BusinessObjectFormatEntity> businessObjectFormatEntity = criteria
            .from(BusinessObjectFormatEntity.class);

    // Join to the other tables we can filter on.
    Join<BusinessObjectFormatEntity, FileTypeEntity> fileTypeEntity = businessObjectFormatEntity
            .join(BusinessObjectFormatEntity_.fileType);
    Join<BusinessObjectFormatEntity, BusinessObjectDefinitionEntity> businessObjectDefinitionEntity = businessObjectFormatEntity
            .join(BusinessObjectFormatEntity_.businessObjectDefinition);

    // Create the standard restrictions (i.e. the standard where clauses).
    // Please note that we specify not to ignore the business object format version.
    Predicate queryRestriction = getQueryRestriction(builder, businessObjectFormatEntity, fileTypeEntity,
            businessObjectDefinitionEntity, businessObjectFormatKey, false);

    // If a business format version was not specified, use the latest one.
    if (businessObjectFormatKey.getBusinessObjectFormatVersion() == null) {
        queryRestriction = builder.and(queryRestriction,
                builder.isTrue(businessObjectFormatEntity.get(BusinessObjectFormatEntity_.latestVersion)));
    }

    criteria.select(businessObjectFormatEntity).where(queryRestriction);

    return executeSingleResultQuery(criteria,
            String.format("Found more than one business object format instance with parameters "
                    + "{namespace=\"%s\", businessObjectDefinitionName=\"%s\", businessObjectFormatUsage=\"%s\", businessObjectFormatFileType=\"%s\", "
                    + "businessObjectFormatVersion=\"%d\"}.", businessObjectFormatKey.getNamespace(),
                    businessObjectFormatKey.getBusinessObjectDefinitionName(),
                    businessObjectFormatKey.getBusinessObjectFormatUsage(),
                    businessObjectFormatKey.getBusinessObjectFormatFileType(),
                    businessObjectFormatKey.getBusinessObjectFormatVersion()));
}

From source file:org.finra.dm.dao.impl.DmDaoImpl.java

/**
 * {@inheritDoc}/* w  ww  .  j av a 2 s.  c o  m*/
 */
@Override
public List<BusinessObjectFormatKey> getBusinessObjectFormats(
        BusinessObjectDefinitionKey businessObjectDefinitionKey, boolean latestBusinessObjectFormatVersion) {
    // Create the criteria builder and a tuple style criteria query.
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Tuple> criteria = builder.createTupleQuery();

    // The criteria root is the business object format.
    Root<BusinessObjectFormatEntity> businessObjectFormatEntity = criteria
            .from(BusinessObjectFormatEntity.class);

    // Join to the other tables we can filter on.
    Join<BusinessObjectFormatEntity, BusinessObjectDefinitionEntity> businessObjectDefinitionEntity = businessObjectFormatEntity
            .join(BusinessObjectFormatEntity_.businessObjectDefinition);
    Join<BusinessObjectFormatEntity, FileTypeEntity> fileTypeEntity = businessObjectFormatEntity
            .join(BusinessObjectFormatEntity_.fileType);
    Join<BusinessObjectDefinitionEntity, NamespaceEntity> namespaceEntity = businessObjectDefinitionEntity
            .join(BusinessObjectDefinitionEntity_.namespace);

    // Get the columns.
    Path<String> namespaceCodeColumn = namespaceEntity.get(NamespaceEntity_.code);
    Path<String> businessObjectDefinitionNameColumn = businessObjectDefinitionEntity
            .get(BusinessObjectDefinitionEntity_.name);
    Path<String> businessObjectFormatUsageColumn = businessObjectFormatEntity
            .get(BusinessObjectFormatEntity_.usage);
    Path<String> fileTypeCodeColumn = fileTypeEntity.get(FileTypeEntity_.code);
    Path<Integer> businessObjectFormatVersionColumn = businessObjectFormatEntity
            .get(BusinessObjectFormatEntity_.businessObjectFormatVersion);
    Expression<Integer> maxBusinessObjectFormatVersionExpression = builder
            .max(businessObjectFormatEntity.get(BusinessObjectFormatEntity_.businessObjectFormatVersion));

    // Create the standard restrictions (i.e. the standard where clauses).
    Predicate queryRestriction = builder.equal(builder.upper(namespaceEntity.get(NamespaceEntity_.code)),
            businessObjectDefinitionKey.getNamespace().toUpperCase());
    queryRestriction = builder.and(queryRestriction,
            builder.equal(
                    builder.upper(businessObjectDefinitionEntity.get(BusinessObjectDefinitionEntity_.name)),
                    businessObjectDefinitionKey.getBusinessObjectDefinitionName().toUpperCase()));

    // Add the select clause.
    criteria.multiselect(namespaceCodeColumn, businessObjectDefinitionNameColumn,
            businessObjectFormatUsageColumn, fileTypeCodeColumn,
            latestBusinessObjectFormatVersion ? maxBusinessObjectFormatVersionExpression
                    : businessObjectFormatVersionColumn);

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

    // If only the latest (maximum) business object format versions to be returned, create and apply the group by clause.
    if (latestBusinessObjectFormatVersion) {
        List<Expression<?>> grouping = new ArrayList<>();
        grouping.add(namespaceCodeColumn);
        grouping.add(businessObjectDefinitionNameColumn);
        grouping.add(businessObjectFormatUsageColumn);
        grouping.add(fileTypeCodeColumn);
        criteria.groupBy(grouping);
    }

    // Add the order by clause.
    List<Order> orderBy = new ArrayList<>();
    orderBy.add(builder.asc(businessObjectFormatUsageColumn));
    orderBy.add(builder.asc(fileTypeCodeColumn));
    if (!latestBusinessObjectFormatVersion) {
        orderBy.add(builder.asc(businessObjectFormatVersionColumn));
    }
    criteria.orderBy(orderBy);

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

    // Populate the "keys" objects from the returned tuples (i.e. 1 tuple for each row).
    List<BusinessObjectFormatKey> businessObjectFormatKeys = new ArrayList<>();
    for (Tuple tuple : tuples) {
        BusinessObjectFormatKey businessObjectFormatKey = new BusinessObjectFormatKey();
        businessObjectFormatKeys.add(businessObjectFormatKey);
        businessObjectFormatKey.setNamespace(tuple.get(namespaceCodeColumn));
        businessObjectFormatKey.setBusinessObjectDefinitionName(tuple.get(businessObjectDefinitionNameColumn));
        businessObjectFormatKey.setBusinessObjectFormatUsage(tuple.get(businessObjectFormatUsageColumn));
        businessObjectFormatKey.setBusinessObjectFormatFileType(tuple.get(fileTypeCodeColumn));
        businessObjectFormatKey.setBusinessObjectFormatVersion(
                tuple.get(latestBusinessObjectFormatVersion ? maxBusinessObjectFormatVersionExpression
                        : businessObjectFormatVersionColumn));
    }

    return businessObjectFormatKeys;
}

From source file:org.finra.dm.dao.impl.DmDaoImpl.java

/**
 * Builds a query restriction predicate for the specified business object format entity as per business object format key values.
 *
 * @param builder the criteria builder/* w  w  w  . j  av  a  2 s . c  o  m*/
 * @param businessObjectFormatEntity the business object format entity that appears in the from clause
 * @param fileTypeEntity the file type entity that appears in the from clause
 * @param businessObjectDefinitionEntity the business object definition entity that appears in the from clause
 * @param businessObjectFormatKey the business object format key
 * @param ignoreBusinessObjectFormatVersion specifies whether to ignore the business object format version when building the predicate
 *
 * @return the query restriction predicate
 */
private Predicate getQueryRestriction(CriteriaBuilder builder,
        From<?, BusinessObjectFormatEntity> businessObjectFormatEntity, From<?, FileTypeEntity> fileTypeEntity,
        From<?, BusinessObjectDefinitionEntity> businessObjectDefinitionEntity,
        BusinessObjectFormatKey businessObjectFormatKey, boolean ignoreBusinessObjectFormatVersion) {
    // Join to the other tables we can filter on.
    Join<BusinessObjectDefinitionEntity, NamespaceEntity> namespaceEntity = businessObjectDefinitionEntity
            .join(BusinessObjectDefinitionEntity_.namespace);

    // Create the standard restrictions based on the business object format key values (i.e. the standard where clauses).

    // Create a restriction on namespace code.
    Predicate predicate = builder.equal(builder.upper(namespaceEntity.get(NamespaceEntity_.code)),
            businessObjectFormatKey.getNamespace().toUpperCase());

    // Create and append a restriction on business object definition name.
    predicate = builder.and(predicate,
            builder.equal(
                    builder.upper(businessObjectDefinitionEntity.get(BusinessObjectDefinitionEntity_.name)),
                    businessObjectFormatKey.getBusinessObjectDefinitionName().toUpperCase()));

    // Create and append a restriction on business object format usage.
    predicate = builder.and(predicate,
            builder.equal(builder.upper(businessObjectFormatEntity.get(BusinessObjectFormatEntity_.usage)),
                    businessObjectFormatKey.getBusinessObjectFormatUsage().toUpperCase()));

    // Create and append a restriction on business object format file type.
    predicate = builder.and(predicate, builder.equal(builder.upper(fileTypeEntity.get(FileTypeEntity_.code)),
            businessObjectFormatKey.getBusinessObjectFormatFileType().toUpperCase()));

    // If specified, create and append a restriction on business object format version.
    if (!ignoreBusinessObjectFormatVersion
            && businessObjectFormatKey.getBusinessObjectFormatVersion() != null) {
        predicate = builder.and(predicate,
                builder.equal(
                        businessObjectFormatEntity.get(BusinessObjectFormatEntity_.businessObjectFormatVersion),
                        businessObjectFormatKey.getBusinessObjectFormatVersion()));
    }

    return predicate;
}

From source file:org.finra.dm.dao.impl.DmDaoImpl.java

/**
 * {@inheritDoc}//from w  w  w .j  ava 2  s  .co m
 */
@Override
public ExpectedPartitionValueEntity getExpectedPartitionValue(
        ExpectedPartitionValueKey expectedPartitionValueKey, int offset) {
    // Create the criteria builder and the criteria.
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<ExpectedPartitionValueEntity> criteria = builder
            .createQuery(ExpectedPartitionValueEntity.class);

    // The criteria root is the expected partition value.
    Root<ExpectedPartitionValueEntity> expectedPartitionValueEntity = criteria
            .from(ExpectedPartitionValueEntity.class);

    // Join to the other tables we can filter on.
    Join<ExpectedPartitionValueEntity, PartitionKeyGroupEntity> partitionKeyGroupEntity = expectedPartitionValueEntity
            .join(ExpectedPartitionValueEntity_.partitionKeyGroup);

    // Add a restriction to filter case insensitive groups that match the user specified group.
    Predicate whereRestriction = builder.equal(
            builder.upper(partitionKeyGroupEntity.get(PartitionKeyGroupEntity_.partitionKeyGroupName)),
            expectedPartitionValueKey.getPartitionKeyGroupName().toUpperCase());

    // Depending on the offset, we might need to order the records in the query.
    Order orderByExpectedPartitionValue = null;

    // Add additional restrictions to handle expected partition value and an optional offset.
    if (offset == 0) {
        // Since there is no offset, we need to match the expected partition value exactly.
        whereRestriction = builder.and(whereRestriction,
                builder.equal(expectedPartitionValueEntity.get(ExpectedPartitionValueEntity_.partitionValue),
                        expectedPartitionValueKey.getExpectedPartitionValue()));
    } else if (offset > 0) {
        // For a positive offset value, add a restriction to filter expected partition values that are >= the user specified expected partition value.
        whereRestriction = builder.and(whereRestriction,
                builder.greaterThanOrEqualTo(
                        expectedPartitionValueEntity.get(ExpectedPartitionValueEntity_.partitionValue),
                        expectedPartitionValueKey.getExpectedPartitionValue()));

        // Order by expected partition value in ascending order.
        orderByExpectedPartitionValue = builder
                .asc(expectedPartitionValueEntity.get(ExpectedPartitionValueEntity_.partitionValue));
    } else {
        // For a negative offset value, add a restriction to filter expected partition values that are <= the user specified expected partition value.
        whereRestriction = builder.and(whereRestriction,
                builder.lessThanOrEqualTo(
                        expectedPartitionValueEntity.get(ExpectedPartitionValueEntity_.partitionValue),
                        expectedPartitionValueKey.getExpectedPartitionValue()));

        // Order by expected partition value in descending order.
        orderByExpectedPartitionValue = builder
                .desc(expectedPartitionValueEntity.get(ExpectedPartitionValueEntity_.partitionValue));
    }

    // Add the clauses for the query and execute the query.
    if (offset == 0) {
        criteria.select(expectedPartitionValueEntity).where(whereRestriction);

        return executeSingleResultQuery(criteria, String.format(
                "Found more than one expected partition value with parameters {partitionKeyGroupName=\"%s\", expectedPartitionValue=\"%s\"}.",
                expectedPartitionValueKey.getPartitionKeyGroupName(),
                expectedPartitionValueKey.getExpectedPartitionValue()));
    } else {
        criteria.select(expectedPartitionValueEntity).where(whereRestriction)
                .orderBy(orderByExpectedPartitionValue);

        List<ExpectedPartitionValueEntity> resultList = entityManager.createQuery(criteria)
                .setFirstResult(Math.abs(offset)).setMaxResults(1).getResultList();

        return resultList.size() > 0 ? resultList.get(0) : null;
    }
}

From source file:org.finra.dm.dao.impl.DmDaoImpl.java

/**
 * {@inheritDoc}/*  ww w  . j a va 2  s  .co m*/
 */
@Override
public List<ExpectedPartitionValueEntity> getExpectedPartitionValuesByGroupAndRange(
        String partitionKeyGroupName, PartitionValueRange partitionValueRange) {
    // Create the criteria builder and the criteria.
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<ExpectedPartitionValueEntity> criteria = builder
            .createQuery(ExpectedPartitionValueEntity.class);

    // The criteria root is the expected partition value.
    Root<ExpectedPartitionValueEntity> expectedPartitionValueEntity = criteria
            .from(ExpectedPartitionValueEntity.class);

    // Join to the other tables we can filter on.
    Join<ExpectedPartitionValueEntity, PartitionKeyGroupEntity> partitionKeyGroupEntity = expectedPartitionValueEntity
            .join(ExpectedPartitionValueEntity_.partitionKeyGroup);

    // Add a restriction to filter case insensitive groups that match the user specified group.
    Predicate whereRestriction = builder.equal(
            builder.upper(partitionKeyGroupEntity.get(PartitionKeyGroupEntity_.partitionKeyGroupName)),
            partitionKeyGroupName.toUpperCase());

    // If we have a possible partition value range, we need to add additional restrictions.
    if (partitionValueRange != null) {
        // Add a restriction to filter values that are >= the user specified range start value.
        if (StringUtils.isNotBlank(partitionValueRange.getStartPartitionValue())) {
            whereRestriction = builder.and(whereRestriction,
                    builder.greaterThanOrEqualTo(
                            expectedPartitionValueEntity.get(ExpectedPartitionValueEntity_.partitionValue),
                            partitionValueRange.getStartPartitionValue()));
        }

        // Add a restriction to filter values that are <= the user specified range end value.
        if (StringUtils.isNotBlank(partitionValueRange.getEndPartitionValue())) {
            whereRestriction = builder.and(whereRestriction,
                    builder.lessThanOrEqualTo(
                            expectedPartitionValueEntity.get(ExpectedPartitionValueEntity_.partitionValue),
                            partitionValueRange.getEndPartitionValue()));
        }
    }

    // Order the results by partition value.
    Order orderByValue = builder
            .asc(expectedPartitionValueEntity.get(ExpectedPartitionValueEntity_.partitionValue));

    // Add the clauses for the query.
    criteria.select(expectedPartitionValueEntity).where(whereRestriction).orderBy(orderByValue);

    // Execute the query and return the results.
    return entityManager.createQuery(criteria).getResultList();
}