Example usage for javax.persistence.criteria CriteriaBuilder isNull

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

Introduction

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

Prototype

Predicate isNull(Expression<?> x);

Source Link

Document

Create a predicate to test whether the expression is null.

Usage

From source file:org.finra.herd.dao.impl.StorageUnitNotificationRegistrationDaoImpl.java

@Override
public List<NotificationRegistrationKey> getStorageUnitNotificationRegistrationKeysByNotificationFilter(
        StorageUnitNotificationFilter businessObjectDataNotificationFilter) {
    // 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> notificationRegistrationEntityRoot = criteria
            .from(StorageUnitNotificationRegistrationEntity.class);

    // Join to the other tables we can filter on.
    Join<StorageUnitNotificationRegistrationEntity, NamespaceEntity> notificationRegistrationNamespaceEntityJoin = notificationRegistrationEntityRoot
            .join(StorageUnitNotificationRegistrationEntity_.namespace);
    Join<StorageUnitNotificationRegistrationEntity, BusinessObjectDefinitionEntity> businessObjectDefinitionEntity = notificationRegistrationEntityRoot
            .join(StorageUnitNotificationRegistrationEntity_.businessObjectDefinition);
    Join<BusinessObjectDefinitionEntity, NamespaceEntity> businessObjectDefinitionNamespaceEntity = businessObjectDefinitionEntity
            .join(BusinessObjectDefinitionEntity_.namespace);
    Join<StorageUnitNotificationRegistrationEntity, FileTypeEntity> fileTypeEntity = notificationRegistrationEntityRoot
            .join(StorageUnitNotificationRegistrationEntity_.fileType, JoinType.LEFT);

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

    // Create the standard restrictions (i.e. the standard where clauses).
    List<Predicate> predicates = new ArrayList<>();
    predicates.add(//from w w  w .jav  a2s  . c  o  m
            builder.equal(builder.upper(businessObjectDefinitionNamespaceEntity.get(NamespaceEntity_.code)),
                    businessObjectDataNotificationFilter.getNamespace().toUpperCase()));
    predicates.add(builder.equal(
            builder.upper(businessObjectDefinitionEntity.get(BusinessObjectDefinitionEntity_.name)),
            businessObjectDataNotificationFilter.getBusinessObjectDefinitionName().toUpperCase()));
    if (StringUtils.isNotBlank(businessObjectDataNotificationFilter.getBusinessObjectFormatUsage())) {
        predicates.add(builder.or(
                builder.isNull(notificationRegistrationEntityRoot
                        .get(StorageUnitNotificationRegistrationEntity_.usage)),
                builder.equal(
                        builder.upper(notificationRegistrationEntityRoot
                                .get(StorageUnitNotificationRegistrationEntity_.usage)),
                        businessObjectDataNotificationFilter.getBusinessObjectFormatUsage().toUpperCase())));
    }
    if (StringUtils.isNotBlank(businessObjectDataNotificationFilter.getBusinessObjectFormatFileType())) {
        predicates.add(builder.or(
                builder.isNull(notificationRegistrationEntityRoot
                        .get(StorageUnitNotificationRegistrationEntity_.fileType)),
                builder.equal(builder.upper(fileTypeEntity.get(FileTypeEntity_.code)),
                        businessObjectDataNotificationFilter.getBusinessObjectFormatFileType().toUpperCase())));
    }

    // Add the select and where clauses to the query.
    criteria.multiselect(notificationRegistrationNamespaceColumn, notificationRegistrationNameColumn)
            .where(builder.and(predicates.toArray(new Predicate[predicates.size()])));

    // Add the order by clause to the query.
    criteria.orderBy(builder.asc(notificationRegistrationNamespaceColumn),
            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);
}

From source file:org.finra.herd.dao.impl.StorageUnitNotificationRegistrationDaoImpl.java

@Override
public List<StorageUnitNotificationRegistrationEntity> getStorageUnitNotificationRegistrations(
        String notificationEventTypeCode, BusinessObjectDataKey businessObjectDataKey, String storageName,
        String newStorageUnitStatus, String oldStorageUnitStatus, String notificationRegistrationStatus) {
    // Create the criteria builder and the criteria.
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<StorageUnitNotificationRegistrationEntity> criteria = builder
            .createQuery(StorageUnitNotificationRegistrationEntity.class);

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

    // Join to the other tables we can filter on.
    Join<StorageUnitNotificationRegistrationEntity, NamespaceEntity> namespaceEntityJoin = storageUnitNotificationRegistrationEntityRoot
            .join(StorageUnitNotificationRegistrationEntity_.namespace);
    Join<StorageUnitNotificationRegistrationEntity, NotificationEventTypeEntity> notificationEventTypeEntityJoin = storageUnitNotificationRegistrationEntityRoot
            .join(StorageUnitNotificationRegistrationEntity_.notificationEventType);
    Join<StorageUnitNotificationRegistrationEntity, BusinessObjectDefinitionEntity> businessObjectDefinitionEntityJoin = storageUnitNotificationRegistrationEntityRoot
            .join(StorageUnitNotificationRegistrationEntity_.businessObjectDefinition);
    Join<BusinessObjectDefinitionEntity, NamespaceEntity> businessObjectDefinitionNamespaceEntityJoin = businessObjectDefinitionEntityJoin
            .join(BusinessObjectDefinitionEntity_.namespace);
    Join<StorageUnitNotificationRegistrationEntity, StorageEntity> storageEntityJoin = storageUnitNotificationRegistrationEntityRoot
            .join(StorageUnitNotificationRegistrationEntity_.storage);
    Join<StorageUnitNotificationRegistrationEntity, FileTypeEntity> fileTypeEntityJoin = storageUnitNotificationRegistrationEntityRoot
            .join(StorageUnitNotificationRegistrationEntity_.fileType, JoinType.LEFT);
    Join<StorageUnitNotificationRegistrationEntity, StorageUnitStatusEntity> newStorageUnitStatusEntityJoin = storageUnitNotificationRegistrationEntityRoot
            .join(StorageUnitNotificationRegistrationEntity_.newStorageUnitStatus, JoinType.LEFT);
    Join<StorageUnitNotificationRegistrationEntity, StorageUnitStatusEntity> oldStorageUnitStatusEntityJoin = storageUnitNotificationRegistrationEntityRoot
            .join(StorageUnitNotificationRegistrationEntity_.oldStorageUnitStatus, JoinType.LEFT);
    Join<StorageUnitNotificationRegistrationEntity, NotificationRegistrationStatusEntity> notificationRegistrationStatusEntityJoin = storageUnitNotificationRegistrationEntityRoot
            .join(StorageUnitNotificationRegistrationEntity_.notificationRegistrationStatus);

    // Create the standard restrictions (i.e. the standard where clauses).
    List<Predicate> predicates = new ArrayList<>();
    predicates.add(/*from  www.j a va  2s  .  c  om*/
            builder.equal(builder.upper(notificationEventTypeEntityJoin.get(NotificationEventTypeEntity_.code)),
                    notificationEventTypeCode.toUpperCase()));
    predicates.add(
            builder.equal(builder.upper(businessObjectDefinitionNamespaceEntityJoin.get(NamespaceEntity_.code)),
                    businessObjectDataKey.getNamespace().toUpperCase()));
    predicates.add(builder.equal(
            builder.upper(businessObjectDefinitionEntityJoin.get(BusinessObjectDefinitionEntity_.name)),
            businessObjectDataKey.getBusinessObjectDefinitionName().toUpperCase()));
    predicates.add(builder.equal(builder.upper(storageEntityJoin.get(StorageEntity_.name)),
            storageName.toUpperCase()));
    predicates.add(builder.or(
            builder.isNull(storageUnitNotificationRegistrationEntityRoot
                    .get(StorageUnitNotificationRegistrationEntity_.usage)),
            builder.equal(
                    builder.upper(storageUnitNotificationRegistrationEntityRoot
                            .get(StorageUnitNotificationRegistrationEntity_.usage)),
                    businessObjectDataKey.getBusinessObjectFormatUsage().toUpperCase())));
    predicates.add(builder.or(
            builder.isNull(storageUnitNotificationRegistrationEntityRoot
                    .get(StorageUnitNotificationRegistrationEntity_.fileType)),
            builder.equal(builder.upper(fileTypeEntityJoin.get(FileTypeEntity_.code)),
                    businessObjectDataKey.getBusinessObjectFormatFileType().toUpperCase())));
    predicates.add(builder.or(
            builder.isNull(storageUnitNotificationRegistrationEntityRoot
                    .get(StorageUnitNotificationRegistrationEntity_.businessObjectFormatVersion)),
            builder.equal(
                    storageUnitNotificationRegistrationEntityRoot
                            .get(StorageUnitNotificationRegistrationEntity_.businessObjectFormatVersion),
                    businessObjectDataKey.getBusinessObjectFormatVersion())));
    predicates.add(builder.or(
            builder.isNull(storageUnitNotificationRegistrationEntityRoot
                    .get(StorageUnitNotificationRegistrationEntity_.newStorageUnitStatus)),
            builder.equal(builder.upper(newStorageUnitStatusEntityJoin.get(StorageUnitStatusEntity_.code)),
                    newStorageUnitStatus.toUpperCase())));
    // Please note that old business object data status parameter value is null for a business object data registration event.
    predicates.add(builder.or(
            builder.isNull(storageUnitNotificationRegistrationEntityRoot
                    .get(StorageUnitNotificationRegistrationEntity_.oldStorageUnitStatus)),
            builder.equal(builder.upper(oldStorageUnitStatusEntityJoin.get(StorageUnitStatusEntity_.code)),
                    oldStorageUnitStatus == null ? null : oldStorageUnitStatus.toUpperCase())));
    predicates.add(builder.equal(
            builder.upper(
                    notificationRegistrationStatusEntityJoin.get(NotificationRegistrationStatusEntity_.code)),
            notificationRegistrationStatus.toUpperCase()));

    // Order the results by namespace and notification name.
    List<Order> orderBy = new ArrayList<>();
    orderBy.add(builder.asc(namespaceEntityJoin.get(NamespaceEntity_.code)));
    orderBy.add(builder.asc(storageUnitNotificationRegistrationEntityRoot
            .get(StorageUnitNotificationRegistrationEntity_.name)));

    // Add the clauses for the query.
    criteria.select(storageUnitNotificationRegistrationEntityRoot)
            .where(builder.and(predicates.toArray(new Predicate[predicates.size()]))).orderBy(orderBy);

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

From source file:org.finra.herd.dao.impl.TagDaoImpl.java

@Override
public List<TagChild> getTagsByTagTypeAndParentTagCode(String tagType, String parentTagCode) {
    // 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);

    // Join to the other tables we can filter on.
    Join<TagEntity, TagTypeEntity> tagTypeEntityJoin = tagEntityRoot.join(TagEntity_.tagType);

    // 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(//  w ww .  j a  v  a2s . c  o  m
            builder.equal(builder.upper(tagTypeEntityJoin.get(TagTypeEntity_.code)), tagType.toUpperCase()));

    if (parentTagCode == null) {
        // Parent tag code is not specified, then return all tags with no parents, i.e. root tags.
        predicates.add(builder.isNull(tagEntityRoot.get(TagEntity_.parentTagEntity)));
    } else {
        // Add a restriction for the parent tag code.
        predicates.add(builder.equal(
                builder.upper(tagEntityRoot.get(TagEntity_.parentTagEntity).get(TagEntity_.tagCode)),
                parentTagCode.toUpperCase()));
    }

    // 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 a list of tag entities back.
    List<TagEntity> tagEntities = entityManager.createQuery(criteria).getResultList();

    // Populate tag child objects from the returned tag entities.
    List<TagChild> tagChildren = new ArrayList<>();
    for (TagEntity tagEntity : tagEntities) {
        boolean hasChildren = !tagEntity.getChildrenTagEntities().isEmpty();
        tagChildren.add(new TagChild(new TagKey(tagEntity.getTagType().getCode(), tagEntity.getTagCode()),
                hasChildren));
    }

    return tagChildren;
}

From source file:org.finra.herd.dao.impl.TagDaoImpl.java

@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(/*w w  w. j av a2s.c o m*/
                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();
}

From source file:org.jboss.pnc.datastore.predicates.rsql.RSQLNodeTravellerPredicate.java

public RSQLNodeTravellerPredicate(Class<Entity> entityClass, String rsql) throws RSQLParserException {
    operations.put(RSQLOperators.EQUAL, new AbstractTransformer<Entity>() {
        @Override//from www. j  av  a2  s. c  om
        Predicate transform(Root<Entity> r, Path<?> selectedPath, CriteriaBuilder cb, String operand,
                List<Object> convertedArguments) {
            return cb.equal(selectedPath, convertedArguments.get(0));
        }
    });

    operations.put(RSQLOperators.NOT_EQUAL, new AbstractTransformer<Entity>() {
        @Override
        Predicate transform(Root<Entity> r, Path<?> selectedPath, CriteriaBuilder cb, String operand,
                List<Object> convertedArguments) {
            return cb.notEqual(selectedPath, convertedArguments.get(0));
        }
    });

    operations.put(RSQLOperators.GREATER_THAN, (r, cb, clazz, operand, arguments) -> cb
            .greaterThan((Path) selectWithOperand(r, operand, clazz), arguments.get(0)));
    operations.put(RSQLOperators.GREATER_THAN_OR_EQUAL, (r, cb, clazz, operand, arguments) -> cb
            .greaterThanOrEqualTo((Path) selectWithOperand(r, operand, clazz), arguments.get(0)));
    operations.put(RSQLOperators.LESS_THAN, (r, cb, clazz, operand, arguments) -> cb
            .lessThan((Path) selectWithOperand(r, operand, clazz), arguments.get(0)));
    operations.put(RSQLOperators.LESS_THAN_OR_EQUAL, (r, cb, clazz, operand, arguments) -> cb
            .lessThanOrEqualTo((Path) selectWithOperand(r, operand, clazz), arguments.get(0)));
    operations.put(RSQLOperators.IN,
            (r, cb, clazz, operand, arguments) -> ((Path) selectWithOperand(r, operand, clazz)).in(arguments));
    operations.put(RSQLOperators.NOT_IN, (r, cb, clazz, operand, arguments) -> cb
            .not(((Path) selectWithOperand(r, operand, clazz)).in(arguments)));
    operations.put(LIKE,
            (r, cb, clazz, operand, arguments) -> cb.like(cb.lower((Path) selectWithOperand(r, operand, clazz)),
                    preprocessLikeOperatorArgument(arguments.get(0).toLowerCase())));
    operations.put(IS_NULL, (r, cb, clazz, operand, arguments) -> {
        if (Boolean.parseBoolean(arguments.get(0))) {
            return cb.isNull((Path) selectWithOperand(r, operand, clazz));
        } else {
            return cb.isNotNull((Path) selectWithOperand(r, operand, clazz));
        }
    });

    Set<ComparisonOperator> operators = RSQLOperators.defaultOperators();
    operators.add(LIKE);
    operators.add(IS_NULL);

    rootNode = new RSQLParser(operators).parse(preprocessRSQL(rsql));
    selectingClass = entityClass;
}

From source file:org.kuali.student.r2.core.scheduling.dao.TimeSlotDao.java

public List<TimeSlotEntity> getByTimeSlotTypeWeekdaysStartTimeAndEndTime(String timeSlotType, String weekdays,
        Long startTime, Long endTime) {
    CriteriaBuilder builder = em.getCriteriaBuilder();
    CriteriaQuery<TimeSlotEntity> query = builder.createQuery(TimeSlotEntity.class);
    Root<TimeSlotEntity> root = query.from(TimeSlotEntity.class);
    query.select(root);//from w w w  .ja  v a2  s. co  m

    List<Predicate> predicateList = new ArrayList<Predicate>();

    predicateList.add(builder.equal(root.get("timeSlotType"), timeSlotType));

    if (StringUtils.isNotBlank(weekdays)) {
        predicateList.add(builder.equal(root.get("weekdays"), weekdays));
    } else {
        predicateList.add(builder.isNull(root.get("weekdays")));
    }

    if (startTime != null) {
        predicateList.add(builder.equal(root.get("startTimeMillis"), startTime));
    } else {
        predicateList.add(builder.isNull(root.get("startTimeMillis")));
    }

    if (endTime != null) {
        predicateList.add(builder.equal(root.get("endTimeMillis"), endTime));
    } else {
        predicateList.add(builder.isNull(root.get("endTimeMillis")));
    }

    Predicate[] predicates = new Predicate[predicateList.size()];
    predicateList.toArray(predicates);

    query.where(predicates);

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

From source file:org.medici.bia.dao.image.ImageDAOJpaImpl.java

/**
 * {@inheritDoc}/*w w  w . j  a v a 2  s .  c om*/
 */
@Override
public List<Image> findImages(Integer volNum, String volLetExt) throws PersistenceException {
    // Create criteria objects
    CriteriaBuilder criteriaBuilder = getEntityManager().getCriteriaBuilder();
    CriteriaQuery<Image> criteriaQuery = criteriaBuilder.createQuery(Image.class);
    Root<Image> root = criteriaQuery.from(Image.class);

    // Define predicate's elements
    ParameterExpression<Integer> parameterVolNum = criteriaBuilder.parameter(Integer.class, "volNum");
    ParameterExpression<String> parameterVolLeText = StringUtils.isEmpty("volLetExt") ? null
            : criteriaBuilder.parameter(String.class, "volLetExt");

    criteriaQuery.where(criteriaBuilder.and(criteriaBuilder.equal(root.get("volNum"), parameterVolNum),
            StringUtils.isEmpty(volLetExt) ? criteriaBuilder.isNull(root.get("volLetExt"))
                    : criteriaBuilder.equal(root.get("volLetExt"), parameterVolLeText)));

    // Set values in predicate's elements  
    TypedQuery<Image> typedQuery = getEntityManager().createQuery(criteriaQuery);
    typedQuery.setParameter("volNum", volNum);
    if (!StringUtils.isEmpty(volLetExt)) {
        typedQuery.setParameter("volLetExt", volLetExt);
    }

    return typedQuery.getResultList();
}

From source file:org.medici.bia.dao.image.ImageDAOJpaImpl.java

/**
 * {@inheritDoc}/*from ww  w.jav a  2  s  . c  om*/
 */
@SuppressWarnings("rawtypes")
@Override
public Page findImages(Integer volNum, String volLetExt, PaginationFilter paginationFilter)
        throws PersistenceException {
    // Create criteria objects
    CriteriaBuilder criteriaBuilder = getEntityManager().getCriteriaBuilder();

    Page page = new Page(paginationFilter);

    if (paginationFilter.getTotal() == null) {
        CriteriaQuery<Long> criteriaQueryCount = criteriaBuilder.createQuery(Long.class);
        Root<Image> rootCount = criteriaQueryCount.from(Image.class);
        criteriaQueryCount.select(criteriaBuilder.count(rootCount));

        // Define predicate's elements
        ParameterExpression<Integer> parameterVolNum = criteriaBuilder.parameter(Integer.class, "volNum");
        ParameterExpression<String> parameterVolLeText = StringUtils.isEmpty("volLetExt") ? null
                : criteriaBuilder.parameter(String.class, "volLetExt");

        criteriaQueryCount
                .where(criteriaBuilder.and(criteriaBuilder.equal(rootCount.get("volNum"), parameterVolNum),
                        StringUtils.isEmpty(volLetExt) ? criteriaBuilder.isNull(rootCount.get("volLetExt"))
                                : criteriaBuilder.equal(rootCount.get("volLetExt"), parameterVolLeText)));

        TypedQuery typedQueryCount = getEntityManager().createQuery(criteriaQueryCount);
        typedQueryCount.setParameter("volNum", volNum);
        if (!StringUtils.isEmpty(volLetExt)) {
            typedQueryCount.setParameter("volLetExt", volLetExt);
        }
        page.setTotal(new Long((Long) typedQueryCount.getSingleResult()));
    }

    CriteriaQuery<Image> criteriaQuery = criteriaBuilder.createQuery(Image.class);
    Root<Image> root = criteriaQuery.from(Image.class);

    // Define predicate's elements
    ParameterExpression<Integer> parameterVolNum = criteriaBuilder.parameter(Integer.class, "volNum");
    ParameterExpression<String> parameterVolLeText = StringUtils.isEmpty("volLetExt") ? null
            : criteriaBuilder.parameter(String.class, "volLetExt");

    //We need to duplicate predicates beacause they are link to Root element
    criteriaQuery.where(criteriaBuilder.and(criteriaBuilder.equal(root.get("volNum"), parameterVolNum),
            StringUtils.isEmpty(volLetExt) ? criteriaBuilder.isNull(root.get("volLetExt"))
                    : criteriaBuilder.equal(root.get("volLetExt"), parameterVolLeText)));

    // Set values in predicate's elements  
    TypedQuery<Image> typedQuery = getEntityManager().createQuery(criteriaQuery);
    typedQuery.setParameter("volNum", volNum);
    if (!StringUtils.isEmpty(volLetExt)) {
        typedQuery.setParameter("volLetExt", volLetExt);
    }

    //Pagination will work with index [1 ... total] and not [0 ... total1-] 
    typedQuery.setFirstResult(paginationFilter.getFirstRecord() - 1);
    typedQuery.setMaxResults(paginationFilter.getLength());
    page.setList(typedQuery.getResultList());

    return page;
}

From source file:org.medici.bia.dao.image.ImageDAOJpaImpl.java

/**
 * {@inheritDoc}//w  w  w  .  j  a  v  a2  s  .  c o  m
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public FoliosInformations findVolumeFoliosInformations(Integer volNum, String volLetExt)
        throws PersistenceException {
    FoliosInformations foliosInformations = new FoliosInformations();

    CriteriaBuilder criteriaBuilder = getEntityManager().getCriteriaBuilder();

    CriteriaQuery<Long> criteriaQueryCount = criteriaBuilder.createQuery(Long.class);
    Root<Image> rootCount = criteriaQueryCount.from(Image.class);
    criteriaQueryCount.select(criteriaBuilder.count(rootCount));

    // Define predicate's elements
    ParameterExpression<Integer> parameterVolNum = criteriaBuilder.parameter(Integer.class, "volNum");
    ParameterExpression<String> parameterVolLeText = StringUtils.isEmpty("volLetExt") ? null
            : criteriaBuilder.parameter(String.class, "volLetExt");

    criteriaQueryCount
            .where(criteriaBuilder.and(criteriaBuilder.equal(rootCount.get("volNum"), parameterVolNum),
                    StringUtils.isEmpty(volLetExt) ? criteriaBuilder.isNull(rootCount.get("volLetExt"))
                            : criteriaBuilder.equal(rootCount.get("volLetExt"), parameterVolLeText)));

    TypedQuery typedQueryCount = getEntityManager().createQuery(criteriaQueryCount);
    typedQueryCount.setParameter("volNum", volNum);
    if (!StringUtils.isEmpty(volLetExt))
        typedQueryCount.setParameter("volLetExt", volLetExt);
    foliosInformations.setTotal((Long) typedQueryCount.getSingleResult());

    StringBuilder stringBuilder = new StringBuilder(
            "SELECT imageType, imageRectoVerso, max(imageProgTypeNum) FROM Image WHERE volNum=:volNum and volLetExt ");
    if (!StringUtils.isEmpty(volLetExt))
        stringBuilder.append(" = :volLetExt");
    else
        stringBuilder.append(" is null");
    stringBuilder.append(" GROUP BY imageType, imageRectoVerso");

    Query query = getEntityManager().createQuery(stringBuilder.toString());
    query.setParameter("volNum", volNum);
    if (!StringUtils.isEmpty(volLetExt)) {
        query.setParameter("volLetExt", volLetExt);
    }

    List<Object[]> result = (List<Object[]>) query.getResultList();

    // We init every partial-total
    foliosInformations.setTotalRubricario(new Long(0));
    foliosInformations.setTotalCarta(new Long(0));
    foliosInformations.setTotalAppendix(new Long(0));
    foliosInformations.setTotalOther(new Long(0));
    foliosInformations.setTotalGuardia(new Long(0));
    foliosInformations.setTotalMissingFolios(0);
    // We set new partial-total values 
    for (int i = 0; i < result.size(); i++) {
        // This is an array defined as [ImageType, Count by ImageType]
        Object[] singleGroup = result.get(i);

        if (((ImageType) singleGroup[0]).equals(ImageType.R)) {
            if (foliosInformations.getTotalRubricario() < new Long(singleGroup[2].toString())) {
                foliosInformations.setTotalRubricario(new Long(singleGroup[2].toString()));
            }
        } else if (((ImageType) singleGroup[0]).equals(ImageType.C)) {
            if (foliosInformations.getTotalCarta() < new Long(singleGroup[2].toString())) {
                foliosInformations.setTotalCarta(new Long(singleGroup[2].toString()));
            }
        } else if (((ImageType) singleGroup[0]).equals(ImageType.A)) {
            if (foliosInformations.getTotalAppendix() < new Long(singleGroup[2].toString())) {
                foliosInformations.setTotalAppendix(new Long(singleGroup[2].toString()));
            }
        } else if (((ImageType) singleGroup[0]).equals(ImageType.O)) {
            if (foliosInformations.getTotalOther() < new Long(singleGroup[2].toString())) {
                foliosInformations.setTotalOther(new Long(singleGroup[2].toString()));
            }
        } else if (((ImageType) singleGroup[0]).equals(ImageType.G)) {
            if (foliosInformations.getTotalGuardia() < new Long(singleGroup[2].toString())) {
                foliosInformations.setTotalGuardia(new Long(singleGroup[2].toString()));
            }
        }
    }

    // Calculating missing folios start
    stringBuilder = new StringBuilder(
            "SELECT DISTINCT(imageProgTypeNum) FROM Image WHERE volNum = :volNum AND volLetExt ");
    if (!StringUtils.isEmpty(volLetExt))
        stringBuilder.append(" = :volLetExt");
    else
        stringBuilder.append(" IS NULL");
    stringBuilder.append(" AND imageType = 'C'"); // we search only for folios
    stringBuilder.append(" ORDER BY imageProgTypeNum ASC");

    query = getEntityManager().createQuery(stringBuilder.toString());
    query.setParameter("volNum", volNum);
    if (!StringUtils.isEmpty(volLetExt)) {
        query.setParameter("volLetExt", volLetExt);
    }
    List<Integer> foliosOnVolume = (List<Integer>) query.getResultList();

    for (long i = 1; i <= foliosInformations.getTotalCarta(); i++) {
        for (int j = 0; j < foliosOnVolume.size(); j++) {
            if (foliosOnVolume.get(j) == i) {
                break;
            } else if (foliosOnVolume.get(j) > i) {
                foliosInformations.setTotalMissingFolios(foliosInformations.getTotalMissingFolios() + 1);
                //LP : Missing numbering is first counter!!!!
                foliosInformations.getMissingNumberingFolios().add(((Long) i).intValue());
                break;
            }
        }

    }
    // Calculating missing folios end

    //Extracting misnumbered Folios...
    stringBuilder = new StringBuilder(
            "SELECT concat(imageProgTypeNum, missedNumbering) FROM Image WHERE volNum=:volNum and volLetExt ");
    if (!StringUtils.isEmpty(volLetExt))
        stringBuilder.append(" = :volLetExt");
    else
        stringBuilder.append(" is null");
    stringBuilder.append(" and missedNumbering is not null ORDER BY imageProgTypeNum ASC");

    query = getEntityManager().createQuery(stringBuilder.toString());
    query.setParameter("volNum", volNum);
    if (!StringUtils.isEmpty(volLetExt)) {
        query.setParameter("volLetExt", volLetExt);
    }

    foliosInformations.setMisnumberedFolios((List<String>) query.getResultList());

    return foliosInformations;
}

From source file:org.medici.bia.dao.image.ImageDAOJpaImpl.java

/**
 * {@inheritDoc}//from  www. ja  v  a 2  s  .c  o m
 */
//@SuppressWarnings("unchecked")
public List<VolumeInsert> findVolumeInserts(Integer volNum, String volLetExt) {
    CriteriaBuilder criteriaBuilder = getEntityManager().getCriteriaBuilder();

    ParameterExpression<Integer> parameterVolNum = criteriaBuilder.parameter(Integer.class, "volNum");
    ParameterExpression<String> parameterVolLeText = StringUtils.isEmpty("volLetExt") ? null
            : criteriaBuilder.parameter(String.class, "volLetExt");

    CriteriaQuery<VolumeInsert> cq = criteriaBuilder.createQuery(VolumeInsert.class);
    Root<Image> root = cq.from(Image.class);

    cq.select(criteriaBuilder.construct(VolumeInsert.class, root.get("volNum"), root.get("volLetExt"),
            root.get("insertNum"), root.get("insertLet"))).distinct(true);
    cq.where(criteriaBuilder.and(criteriaBuilder.equal(root.get("volNum"), parameterVolNum),
            StringUtils.isEmpty(volLetExt) ? criteriaBuilder.isNull(root.get("volLetExt"))
                    : criteriaBuilder.equal(root.get("volLetExt"), parameterVolLeText),
            criteriaBuilder.isNotNull(root.get("insertNum"))));
    cq.orderBy(criteriaBuilder.asc(root.get("insertNum")), criteriaBuilder.asc(root.get("insertLet")));

    /* The above query is equivalent to the following:
     * SELECT DISTINCT volNum, volLetExt, insertNum, insertLet FROM Image
     * WHERE 
     *        volNum = :volNum
     *   AND volLetExt (<nullable> ? 'IS NULL' : ':volLetExt')
     *   AND insertNum IS NOT NULL
     * ORDER BY
     *       insertNum ASC,
     *       insertLet ASC
     */

    TypedQuery<VolumeInsert> tq = getEntityManager().createQuery(cq);
    tq.setParameter("volNum", volNum);
    if (!StringUtils.isEmpty(volLetExt))
        tq.setParameter("volLetExt", volLetExt);

    return tq.getResultList();
}