Java Code Examples for javax.persistence.criteria.Expression#in()

The following examples show how to use javax.persistence.criteria.Expression#in() . 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: HibernateTrackedEntityDataValueAuditStore.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private  List<Predicate> getTrackedEntityDataValueAuditCriteria( List<DataElement> dataElements, List<ProgramStageInstance> programStageInstances,
    AuditType auditType, CriteriaBuilder builder, Root<TrackedEntityDataValueAudit> root )
{
    List<Predicate> predicates = new ArrayList<>();

    if ( dataElements != null && !dataElements.isEmpty() )
    {
        Expression<DataElement> dataElementExpression = root.get( "dataElement" );
        Predicate dataElementPredicate = dataElementExpression.in( dataElements );
        predicates.add( dataElementPredicate );
    }

    if ( programStageInstances != null && !programStageInstances.isEmpty() )
    {
        Expression<DataElement> psiExpression = root.get( "programStageInstance" );
        Predicate psiPredicate = psiExpression.in( programStageInstances );
        predicates.add( psiPredicate );
    }

    if ( auditType != null )
    {
        predicates.add( builder.equal( root.get( "auditType" ), auditType ) );
    }

    return predicates;
}
 
Example 2
Source File: TagDaoImpl.java    From herd with Apache License 2.0 6 votes vote down vote up
@Override
public List<TagEntity> getTagsByIds(List<Long> ids)
{
    // Create the criteria builder and a tuple style criteria query.
    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);

    // Create the standard restrictions (i.e. the standard where clauses).
    Expression<Long> expression = tagEntityRoot.get(TagEntity_.id);
    Predicate queryRestriction = expression.in(ids);

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

    return entityManager.createQuery(criteria).getResultList();
}
 
Example 3
Source File: BusinessObjectDefinitionDaoImpl.java    From herd with Apache License 2.0 6 votes vote down vote up
@Override
public List<BusinessObjectDefinitionEntity> getAllBusinessObjectDefinitionsByIds(List<Long> ids)
{
    // Create the criteria builder and a tuple style criteria query.
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<BusinessObjectDefinitionEntity> criteria = builder.createQuery(BusinessObjectDefinitionEntity.class);

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

    // Create the standard restrictions (i.e. the standard where clauses).
    Expression<Long> expression = businessObjectDefinitionEntityRoot.get(BusinessObjectDefinitionEntity_.id);
    Predicate queryRestriction = expression.in(ids);

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

    return entityManager.createQuery(criteria).getResultList();
}
 
Example 4
Source File: ColumnFilter.java    From spring-data-jpa-datatables with Apache License 2.0 6 votes vote down vote up
@Override
public javax.persistence.criteria.Predicate createPredicate(From<?, ?> from, CriteriaBuilder criteriaBuilder, String attributeName) {
    Expression<?> expression = from.get(attributeName);

    if (values.isEmpty()) {
        return addNullCase ? expression.isNull() : criteriaBuilder.conjunction();
    } else if (isBasicFilter()) {
        return super.createPredicate(from, criteriaBuilder, attributeName);
    }

    javax.persistence.criteria.Predicate predicate;
    if (isBooleanComparison) {
        predicate = expression.in(booleanValues);
    } else {
        predicate = expression.as(String.class).in(values);
    }
    if (addNullCase) predicate = criteriaBuilder.or(predicate, expression.isNull());

    return predicate;
}
 
Example 5
Source File: BuildRecordPredicates.java    From pnc with Apache License 2.0 6 votes vote down vote up
public static Predicate<BuildRecord> withBuildConfigurationIdRev(List<IdRev> buildConfigurationsWithIdRevs) {
    if (buildConfigurationsWithIdRevs.isEmpty()) {
        return Predicate.nonMatching();
    }

    List<String> idRevs = buildConfigurationsWithIdRevs.stream()
            .map(idRev -> idRev.getId() + "-" + idRev.getRev())
            .collect(Collectors.toList());

    return (root, query, cb) -> {
        Expression<String> concat = cb.concat(root.get(BuildRecord_.buildConfigurationId).as(String.class), "-");
        Expression<String> buildRecordIdRev = cb
                .concat(concat, root.get(BuildRecord_.buildConfigurationRev).as(String.class));
        logger.debug("Searching for BuildRecords with {}", idRevs);
        return buildRecordIdRev.in(idRevs);
    };
}
 
Example 6
Source File: RdbmsUtils.java    From modeldb with Apache License 2.0 5 votes vote down vote up
/**
 * Return the where clause predicate based on given parameters
 *
 * @param builder : Hibernate criteria builder
 * @param valueExpression : field value path for criteria query
 * @param operator : operator like EQ, GTE, LE etc.
 * @param operatorValue : field value which set to where clause based on field, Operator and this
 *     value
 * @return {@link Predicate} : return predicate (where clause condition) for criteria query
 */
private static Predicate getOperatorPredicate(
    CriteriaBuilder builder,
    Expression valueExpression,
    Operator operator,
    Object operatorValue) {
  switch (operator.ordinal()) {
    case Operator.GT_VALUE:
      return builder.greaterThan(valueExpression, (Comparable) operatorValue);
    case Operator.GTE_VALUE:
      return builder.greaterThanOrEqualTo(valueExpression, (Comparable) operatorValue);
    case Operator.LT_VALUE:
      return builder.lessThan(valueExpression, (Comparable) operatorValue);
    case Operator.LTE_VALUE:
      return builder.lessThanOrEqualTo(valueExpression, (Comparable) operatorValue);
    case Operator.NE_VALUE:
      return builder.notEqual(valueExpression, operatorValue);
    case Operator.CONTAIN_VALUE:
      return builder.like(
          builder.lower(valueExpression),
          ("%" + Pattern.compile((String) operatorValue) + "%").toLowerCase());
    case Operator.NOT_CONTAIN_VALUE:
      return builder.notLike(
          builder.lower(valueExpression),
          ("%" + Pattern.compile((String) operatorValue) + "%").toLowerCase());
    case Operator.IN_VALUE:
      return valueExpression.in(operatorValue);
    default:
      return builder.equal(valueExpression, operatorValue);
  }
}
 
Example 7
Source File: RdbmsUtils.java    From modeldb with Apache License 2.0 5 votes vote down vote up
private static Predicate getFuzzyUsersQueryPredicate(
    AuthService authService,
    CriteriaBuilder builder,
    Root<?> entityRootPath,
    KeyValueQuery requestedPredicate) {
  if (requestedPredicate.getValue().getKindCase().equals(Value.KindCase.STRING_VALUE)) {
    Operator operator = requestedPredicate.getOperator();
    UserInfoPaginationDTO userInfoPaginationDTO =
        authService.getFuzzyUserInfoList(requestedPredicate.getValue().getStringValue());
    List<UserInfo> userInfoList = userInfoPaginationDTO.getUserInfoList();
    if (userInfoList != null && !userInfoList.isEmpty()) {
      Expression<String> exp = entityRootPath.get(requestedPredicate.getKey());
      List<String> vertaIds =
          userInfoList.stream()
              .map(authService::getVertaIdFromUserInfo)
              .collect(Collectors.toList());
      if (operator.equals(Operator.NOT_CONTAIN) || operator.equals(Operator.NE)) {
        return builder.not(exp.in(vertaIds));
      } else {
        return exp.in(vertaIds);
      }
    }
  } else {
    Status invalidValueTypeError =
        Status.newBuilder()
            .setCode(Code.INVALID_ARGUMENT_VALUE)
            .setMessage("Predicate for the owner search only supporting 'String' value")
            .build();
    throw StatusProto.toStatusRuntimeException(invalidValueTypeError);
  }
  return null;
}
 
Example 8
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 9
Source File: RepositoryDAORdbImpl.java    From modeldb with Apache License 2.0 4 votes vote down vote up
@Override
public ListRepositoriesRequest.Response listRepositories(
    ListRepositoriesRequest request, UserInfo currentLoginUserInfo) throws ModelDBException {
  try (Session session = ModelDBHibernateUtil.getSessionFactory().openSession()) {
    List<String> accessibleResourceIds =
        roleService.getAccessibleResourceIds(
            null,
            new CollaboratorUser(authService, currentLoginUserInfo),
            RepositoryVisibility.PRIVATE,
            ModelDBServiceResourceTypes.REPOSITORY,
            Collections.emptyList());

    if (accessibleResourceIds.isEmpty() && roleService.IsImplemented()) {
      LOGGER.debug("Accessible Repository Ids not found, size 0");
      return ListRepositoriesRequest.Response.newBuilder().setTotalRecords(0).build();
    }

    CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder();
    // Using FROM and JOIN
    CriteriaQuery<RepositoryEntity> criteriaQuery =
        criteriaBuilder.createQuery(RepositoryEntity.class);
    Root<RepositoryEntity> repositoryEntityRoot = criteriaQuery.from(RepositoryEntity.class);
    repositoryEntityRoot.alias(SHORT_NAME);
    List<Predicate> finalPredicatesList = new ArrayList<>();

    if (!request.getWorkspaceName().isEmpty()) {
      WorkspaceDTO workspaceDTO =
          verifyAndGetWorkspaceDTO(
              RepositoryIdentification.newBuilder()
                  .setNamedId(
                      RepositoryNamedIdentification.newBuilder()
                          .setWorkspaceName(request.getWorkspaceName()))
                  .build(),
              false);
      List<KeyValueQuery> workspacePredicates =
          ModelDBUtils.getKeyValueQueriesByWorkspaceDTO(workspaceDTO);
      if (workspacePredicates.size() > 0) {
        Predicate privateWorkspacePredicate =
            criteriaBuilder.equal(
                repositoryEntityRoot.get(ModelDBConstants.WORKSPACE_ID),
                workspacePredicates.get(0).getValue().getStringValue());
        Predicate privateWorkspaceTypePredicate =
            criteriaBuilder.equal(
                repositoryEntityRoot.get(ModelDBConstants.WORKSPACE_TYPE),
                workspacePredicates.get(1).getValue().getNumberValue());
        Predicate privatePredicate =
            criteriaBuilder.and(privateWorkspacePredicate, privateWorkspaceTypePredicate);

        finalPredicatesList.add(privatePredicate);
      }
    }

    if (!accessibleResourceIds.isEmpty()) {
      Expression<String> exp = repositoryEntityRoot.get(ModelDBConstants.ID);
      Predicate predicate2 = exp.in(accessibleResourceIds);
      finalPredicatesList.add(predicate2);
    }

    finalPredicatesList.add(
        criteriaBuilder.equal(repositoryEntityRoot.get(ModelDBConstants.DELETED), false));

    Order orderBy = criteriaBuilder.desc(repositoryEntityRoot.get(ModelDBConstants.DATE_UPDATED));

    Predicate[] predicateArr = new Predicate[finalPredicatesList.size()];
    for (int index = 0; index < finalPredicatesList.size(); index++) {
      predicateArr[index] = finalPredicatesList.get(index);
    }

    Predicate predicateWhereCause = criteriaBuilder.and(predicateArr);
    criteriaQuery.select(repositoryEntityRoot);
    criteriaQuery.where(predicateWhereCause);
    criteriaQuery.orderBy(orderBy);

    Query query = session.createQuery(criteriaQuery);
    LOGGER.debug("Repository final query : {}", query.getQueryString());

    if (request.hasPagination()) {
      // Calculate number of documents to skip
      int pageLimit = request.getPagination().getPageLimit();
      query.setFirstResult((request.getPagination().getPageNumber() - 1) * pageLimit);
      query.setMaxResults(pageLimit);
    }

    List<RepositoryEntity> repositoryEntities = query.list();
    ListRepositoriesRequest.Response.Builder builder =
        ListRepositoriesRequest.Response.newBuilder();

    repositoryEntities.forEach(
        repositoryEntity -> builder.addRepositories(repositoryEntity.toProto()));

    long totalRecords = RdbmsUtils.count(session, repositoryEntityRoot, criteriaQuery);
    builder.setTotalRecords(totalRecords);
    return builder.build();
  } catch (Exception ex) {
    if (ModelDBUtils.needToRetry(ex)) {
      return listRepositories(request, currentLoginUserInfo);
    } else {
      throw ex;
    }
  }
}