Example usage for javax.persistence.metamodel SingularAttribute getName

List of usage examples for javax.persistence.metamodel SingularAttribute getName

Introduction

In this page you can find the example usage for javax.persistence.metamodel SingularAttribute getName.

Prototype

String getName();

Source Link

Document

Return the name of the attribute.

Usage

From source file:org.easy.criteria.CriteriaComposer.java

/**
 * for IN and BETWEEN//from   w  w w. j  av  a2s  . com
 * 
 * @param attribute
 * @param cOperator
 * @param values
 * @param lOperator
 * @return
 */
public <V> CriteriaComposer<E> where(SingularAttribute<? super E, V> attribute, ComparisonOperator cOperator,
        List<V> values) {
    Preconditions.checkArgument(
            cOperator.equals(ComparisonOperator.BETWEEN) || cOperator.equals(ComparisonOperator.IN));
    Preconditions.checkNotNull(attribute);
    Preconditions.checkNotNull(cOperator);

    WhereContainer<E> whereContainer = new WhereContainer<E>(attribute, cOperator, values);

    int index = _wheres.indexOf(whereContainer);

    if (index >= 0)
        _wheres.add(index, whereContainer);
    else
        _wheres.add(whereContainer);

    log.debug("Adding where for " + attribute.getName() + " " + cOperator.toString() + " value count "
            + values.size());

    lastCallType = LastCallType.WHERE;

    return this;
}

From source file:org.easy.criteria.CriteriaComposer.java

/**
 * Adds the attribute to where clause of the entity
 * //from w ww  . j  a v a  2 s .  c o m
 * @param attribute
 * @param cOperator
 * @param value
 * @param lOperator
 * @return
 */
public <V> CriteriaComposer<E> where(SingularAttribute<? super E, V> attribute, ComparisonOperator cOperator,
        V value) {
    Preconditions.checkNotNull(attribute);
    Preconditions.checkNotNull(cOperator);

    WhereContainer<E> whereContainer = new WhereContainer<E>(attribute, cOperator, value);

    int index = _wheres.indexOf(whereContainer);

    if (index >= 0)
        _wheres.add(index, whereContainer);
    else
        _wheres.add(whereContainer);

    log.debug("Adding where for " + attribute.getName() + " " + cOperator.toString() + " value "
            + value.toString());

    lastCallType = LastCallType.WHERE;

    return this;
}

From source file:org.easy.criteria.CriteriaComposer.java

/**
 * for IN and BETWEEN//from   w w w.j  a  va2s.co  m
 * 
 * @param attribute
 * @param nOperator
 * @param cOperator
 * @param values
 * @param lOperator
 * @return
 */
public <V> CriteriaComposer<E> where(SingularAttribute<? super E, V> attribute, NegationOperator nOperator,
        ComparisonOperator cOperator, List<V> values) {
    Preconditions.checkArgument(
            cOperator.equals(ComparisonOperator.BETWEEN) || cOperator.equals(ComparisonOperator.IN));

    Preconditions.checkNotNull(attribute);
    Preconditions.checkNotNull(nOperator);
    Preconditions.checkNotNull(cOperator);

    WhereContainer<E> whereContainer = new WhereContainer<E>(attribute, nOperator, cOperator, values);

    int index = _wheres.indexOf(whereContainer);

    if (index >= 0)
        _wheres.add(index, whereContainer);
    else
        _wheres.add(whereContainer);

    log.debug("Adding where for " + attribute.getName() + " " + cOperator.toString() + " value count "
            + values.size());

    lastCallType = LastCallType.WHERE;

    return this;
}

From source file:org.easy.criteria.CriteriaComposer.java

/**
 * Adds the attribute to where clause of the entity
 * //ww w. ja v a 2s .  c o  m
 * @param attribute
 *            - SingularAttribute of the entity for which this search was
 *            created.
 * @param value
 *            - value to match with the attribute.
 */
public <V> CriteriaComposer<E> where(SingularAttribute<? super E, V> attribute, NegationOperator nOperator,
        ComparisonOperator cOperator, V value) {
    Preconditions.checkNotNull(attribute);
    Preconditions.checkNotNull(nOperator);
    Preconditions.checkNotNull(cOperator);

    WhereContainer<E> whereContainer = new WhereContainer<E>(attribute, nOperator, cOperator, value);

    int index = _wheres.indexOf(whereContainer);

    if (index >= 0)
        _wheres.add(index, whereContainer);
    else
        _wheres.add(whereContainer);

    log.debug("Adding where for " + attribute.getName() + " " + cOperator.toString() + " value "
            + value.toString());

    lastCallType = LastCallType.WHERE;

    return this;
}

From source file:org.easy.criteria.CriteriaComposer.java

/**
 * @param attribute/*from w  w w .  j  av  a 2s . com*/
 * @param cOperator
 * @param subCriteria
 * @param lOperator
 * @return
 */
public <V> CriteriaComposer<E> where(SingularAttribute<? super E, V> attribute, ComparisonOperator cOperator,
        CriteriaComposer<V> subCriteria) {
    Preconditions.checkArgument(cOperator.equals(ComparisonOperator.IN));

    Preconditions.checkNotNull(attribute);
    Preconditions.checkNotNull(cOperator);

    WhereContainer<E> whereContainer = new WhereContainer<E>(attribute, cOperator, subCriteria);

    whereContainer.logicOperator = LogicOperator.AND;

    int index = _wheres.indexOf(whereContainer);

    if (index >= 0)//overwrite
        _wheres.add(index, whereContainer);
    else
        _wheres.add(whereContainer);

    log.debug("Adding where for " + attribute.getName() + " " + cOperator.toString() + " sub criteria "
            + subCriteria);

    lastCallType = LastCallType.WHERE;

    return this;
}

From source file:org.easy.criteria.CriteriaComposer.java

/**
 * @param attribute/* ww w  . j  a v a  2s.  c  o m*/
 * @param nOperator
 * @param cOperator
 * @param subCriteria
 * @param lOperator
 * @return
 */
public <V> CriteriaComposer<E> where(SingularAttribute<? super E, V> attribute, NegationOperator nOperator,
        ComparisonOperator cOperator, CriteriaComposer<V> subCriteria) {
    Preconditions.checkArgument(cOperator.equals(ComparisonOperator.IN));

    Preconditions.checkNotNull(attribute);
    Preconditions.checkNotNull(nOperator);
    Preconditions.checkNotNull(cOperator);

    WhereContainer<E> whereContainer = new WhereContainer<E>(attribute, nOperator, cOperator, subCriteria);

    int index = _wheres.indexOf(whereContainer);

    if (index >= 0)
        _wheres.add(index, whereContainer);
    else
        _wheres.add(whereContainer);

    log.debug("Adding where for " + attribute.getName() + " " + cOperator.toString() + " sub criteria "
            + subCriteria);

    lastCallType = LastCallType.WHERE;

    return this;
}

From source file:org.fornax.cartridges.sculptor.framework.accessimpl.jpa2.JpaHelper.java

@SuppressWarnings({ "rawtypes" })
public static Object getValue(Object entity, SingularAttribute attribute) {
    try {/*from w w w .  j  a v  a 2  s. c o  m*/
        return getValue(entity, attribute.getName());
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:org.gvnix.web.datatables.util.DatatablesUtils.java

/**
 * Execute a select query on entityClass using <a
 * href="http://www.querydsl.com/">Querydsl</a> which enables the
 * construction of type-safe SQL-like queries.
 * /*from   ww w.jav  a2s  . co  m*/
 * @param entity builder for entity to use in search. Represents the entity
 *        and gives access to its properties for query purposes
 * @param filterByAssociations (optional) for each related entity to join
 *        contain as key the name of the association and as value the List
 *        of related entity fields to filter by
 * @param orderByAssociations (optional) for each related entity to order
 *        contain as key the name of the association and as value the List
 *        of related entity fields to order by
 * @param entityManager {@code entityClass} {@link EntityManager}
 * @param datatablesCriterias datatables parameters for query
 * @param basePredicate (optional) base filter conditions
 * @param distinct use distinct query
 * @param conversionService required by filter-by-expression and rows-on-top
 *        (otherwise optional)
 * @param messageSource required by filter-by-expression (otherwise
 *        optional)
 * @param rowsOnTopIds (optional) array with id of rows to show on top of
 *        result list
 * @return
 * @throws IllegalArgumentException
 */
public static <T, E extends Comparable<?>> SearchResults<T> findByCriteria(PathBuilder<T> entity,
        Map<String, List<String>> filterByAssociations, Map<String, List<String>> orderByAssociations,
        EntityManager entityManager, DatatablesCriterias datatablesCriterias, BooleanBuilder basePredicate,
        boolean distinct, ConversionService conversionService, MessageSource messageSource,
        Object[] rowsOnTopIds) throws IllegalArgumentException {
    // Check arguments aren't null
    Assert.notNull(entityManager);
    Assert.notNull(datatablesCriterias);

    // If null, create empty Map to avoid control code overload
    if (CollectionUtils.isEmpty(filterByAssociations)) {
        filterByAssociations = new HashMap<String, List<String>>();
    }
    if (CollectionUtils.isEmpty(orderByAssociations)) {
        orderByAssociations = new HashMap<String, List<String>>();
    }

    // true if data results must be paginated
    boolean isPaged = datatablesCriterias.getDisplaySize() != null && datatablesCriterias.getDisplaySize() > 0;

    // true if the search must take in account all columns
    boolean findInAllColumns = StringUtils.isNotEmpty(datatablesCriterias.getSearch())
            && datatablesCriterias.hasOneFilterableColumn();

    LOGGER.debug("findByCriteria for entity '{}' (paged={} findInAllColumns={})", entity.getType(), isPaged,
            findInAllColumns);

    // ----- Create queries -----

    // query will take in account datatables search, order and paging
    // criterias
    JPAQuery query = new JPAQuery(entityManager);
    query = query.from(entity);

    // baseQuery will use base search values only in order to count
    // all for success paging
    JPAQuery baseQuery = new JPAQuery(entityManager);
    baseQuery = baseQuery.from(entity);

    // ----- Entity associations for Query JOINs, ORDER BY, ... -----

    Map<String, PathBuilder<?>> associationMap = new HashMap<String, PathBuilder<?>>();

    query = prepareQueryAssociationMap(entity, filterByAssociations, datatablesCriterias, findInAllColumns,
            query, associationMap);

    // ----- Query WHERE clauses -----

    // Filters by column. Using BooleanBuilder, a cascading builder for
    // Predicate expressions
    BooleanBuilder filtersByColumnPredicate = new BooleanBuilder();

    // Filters by table (for all columns)
    BooleanBuilder filtersByTablePredicate = new BooleanBuilder();

    try {

        // Build the filters by column expression
        if (datatablesCriterias.hasOneFilteredColumn()) {

            filtersByColumnPredicate = prepareQueryFilterPart(entity, filterByAssociations, datatablesCriterias,
                    associationMap, filtersByColumnPredicate, conversionService, messageSource);
        }

        // Build the query to search the given value in all columns
        filtersByTablePredicate = prepareQuerySearchPart(entity, filterByAssociations, datatablesCriterias,
                findInAllColumns, associationMap, filtersByTablePredicate, conversionService);
    } catch (Exception e) {
        LOGGER.error("Exception preparing filter for entity {}", entity.getType(), e);
        SearchResults<T> searchResults = new SearchResults<T>(new ArrayList<T>(0), 0, isPaged,
                new Long(org.apache.commons.lang3.ObjectUtils
                        .defaultIfNull(datatablesCriterias.getDisplayStart(), 0)),
                new Long(org.apache.commons.lang3.ObjectUtils
                        .defaultIfNull(datatablesCriterias.getDisplaySize(), 0)),
                0);
        return searchResults;
    }

    // ----- Query ORDER BY -----

    List<OrderSpecifier<?>> orderSpecifiersList = prepareQueryOrder(entity, orderByAssociations,
            datatablesCriterias, associationMap);

    // ----- Query results paging -----

    Long offset = null;
    Long limit = null;

    if (isPaged) {
        limit = new Long(datatablesCriterias.getDisplaySize());
    }
    if (datatablesCriterias.getDisplayStart() != null && datatablesCriterias.getDisplayStart() >= 0) {
        offset = new Long(datatablesCriterias.getDisplayStart());
    }

    // ------- manage Rows-on-top ----

    List<T> firstRows = null;

    // Decrease limits if firstRowsIds is used
    if (rowsOnTopIds != null) {
        LOGGER.trace("Prepare rows on top: {}", rowsOnTopIds);

        // Coherce row-on-top ids types
        Object[] cohercedRowsOnTopId = new Object[rowsOnTopIds.length];

        EntityType<? extends T> entityMetamodel = entityManager.getMetamodel().entity(entity.getType());
        // We always have just one id. This id can be an Embedded Id
        Class<?> idType = entityMetamodel.getIdType().getJavaType();
        @SuppressWarnings("unchecked")
        SingularAttribute<? extends T, ?> idAttr = (SingularAttribute<? extends T, ?>) entityMetamodel
                .getId(idType);

        Object curId;
        for (int i = 0; i < rowsOnTopIds.length; i++) {
            curId = rowsOnTopIds[i];
            if (curId.getClass() != idType) {
                cohercedRowsOnTopId[i] = conversionService.convert(curId, idType);
            } else {
                cohercedRowsOnTopId[i] = curId;
            }
        }

        // Create expression for rows-on-top
        BooleanExpression firstRowsInExpression = QuerydslUtils.createCollectionExpression(entity,
                idAttr.getName(), Arrays.asList(cohercedRowsOnTopId));

        LOGGER.trace("Expression for rowsOnTop: {}", firstRowsInExpression);

        // Exclude firstRows from base query
        basePredicate = basePredicate.and(firstRowsInExpression.not());

        LOGGER.trace("basePredicate to exclude rowsOnTop now is: {}", basePredicate);

        // Gets rows on top
        JPAQuery firstRowsQuery = new JPAQuery(entityManager);
        firstRowsQuery = firstRowsQuery.from(entity).where(firstRowsInExpression);

        LOGGER.trace("rowsOnTop query is: {}", firstRowsQuery);

        try {
            // TODO handle fieldSelector
            firstRows = firstRowsQuery.list(entity);
        } catch (PersistenceException exSql) {
            // Log query
            LOGGER.error("Error excecuting SQL for firstRow (sql = '{}' )", firstRowsQuery);
            throw exSql;
        }

        LOGGER.trace("Found {} rows for rowsOnTop", firstRows.size());
        // Adjust limit with rows-on-top found
        if (limit != null) {
            LOGGER.trace("Update main query limit: {} --> {}", limit, limit - firstRows.size());
            limit = limit - firstRows.size();
        }

    }

    // ----- Execute the query -----
    List<T> elements = null;

    // Compose the final query and update query var to be used to count
    // total amount of rows if needed

    if (distinct) {
        LOGGER.trace("Use distinct query!!!");
        query = query.distinct();
    }

    // Predicate for base query
    boolean hasBasePredicate = true;
    if (basePredicate == null) {
        basePredicate = new BooleanBuilder();
        hasBasePredicate = false;
    }

    // query projection to count all entities without paging
    baseQuery.where(basePredicate);

    // query projection to be used to get the results and to count filtered
    // results
    query = query.where(
            basePredicate.and(filtersByColumnPredicate.getValue()).and(filtersByTablePredicate.getValue()));

    // Calculate the total amount of rows taking in account datatables
    // search and paging criterias. When results are paginated we
    // must execute a count query, otherwise the size of matched rows List
    // is the total amount of rows
    long totalResultCount = 0;
    if (isPaged) {
        try {
            totalResultCount = query.count();
        } catch (PersistenceException exSql) {
            // Log query
            LOGGER.error("Error excecuting 'count' SQL: {}", query);
            throw exSql;
        }
    }

    if (offset == null) {
        offset = new Long(0);
    } else if (offset > totalResultCount) {
        // If offset value is bigger than total results,
        // offset needs start on 0
        offset = new Long(0);
    }

    // QueryModifiers combines limit and offset
    QueryModifiers queryModifiers = new QueryModifiers(limit, offset);
    LOGGER.trace("Set limit={} offset={}", limit, offset);

    // List ordered and paginated results. An empty list is returned for no
    // results.
    query = query.orderBy(orderSpecifiersList.toArray(new OrderSpecifier[orderSpecifiersList.size()]));

    LOGGER.debug("Execute query: {}", query);
    try {
        elements = query.restrict(queryModifiers).list(entity);
    } catch (PersistenceException exSql) {
        // Log query
        LOGGER.error("Error excecuting SQL: {}", query);
        throw exSql;
    }

    if (!isPaged) {
        totalResultCount = elements.size();
    }

    long totalBaseCount = totalResultCount;
    if (hasBasePredicate) {
        // Calculate the total amount of entities including base filters
        // only
        LOGGER.trace("Execute count query: {}", baseQuery);
        try {
            totalBaseCount = baseQuery.count();
        } catch (PersistenceException exSql) {
            // Log query
            LOGGER.error("Error excecuting 'count' SQL: {}", baseQuery);
            throw exSql;
        }
        LOGGER.trace("Found : {}", totalBaseCount);
    }

    if (firstRows != null) {
        // Adjust result with rows-on-top
        totalResultCount = totalResultCount + firstRows.size();
        totalBaseCount = totalBaseCount + firstRows.size();
        elements.addAll(0, firstRows);
    }

    // Create a new SearchResults instance
    if (limit == null) {
        limit = totalBaseCount;
    }
    SearchResults<T> searchResults = new SearchResults<T>(elements, totalResultCount, isPaged, offset, limit,
            totalBaseCount);

    LOGGER.debug("findByCriteria: return {} rows from {} (offset={} limit={})", totalResultCount,
            totalBaseCount, offset, limit);
    return searchResults;
}

From source file:org.gvnix.web.datatables.util.impl.DatatablesUtilsBeanImpl.java

/**
 * {@inheritDoc}/*  w  w  w.j  a v  a  2  s .c o  m*/
 */
@Override
public <T, E extends Comparable<?>> SearchResults<T> findByCriteria(PathBuilder<T> entity,
        Map<String, List<String>> filterByAssociations, Map<String, List<String>> orderByAssociations,
        DatatablesCriterias datatablesCriterias, BooleanBuilder basePredicate, boolean distinct,
        Object[] rowsOnTopIds) throws IllegalArgumentException {
    // Check arguments aren't null
    EntityManager entityManager = entityManagerProvider.getEntityManager(entity.getType());
    Assert.notNull(entityManager);
    Assert.notNull(datatablesCriterias);

    // If null, create empty Map to avoid control code overload
    if (CollectionUtils.isEmpty(filterByAssociations)) {
        filterByAssociations = new HashMap<String, List<String>>();
    }
    if (CollectionUtils.isEmpty(orderByAssociations)) {
        orderByAssociations = new HashMap<String, List<String>>();
    }

    // true if data results must be paginated
    boolean isPaged = datatablesCriterias.getDisplaySize() != null && datatablesCriterias.getDisplaySize() > 0;

    // true if the search must take in account all columns
    boolean findInAllColumns = StringUtils.isNotEmpty(datatablesCriterias.getSearch())
            && datatablesCriterias.hasOneFilterableColumn();

    LOGGER.debug("findByCriteria for entity '{}' (paged={} findInAllColumns={})", entity.getType(), isPaged,
            findInAllColumns);

    // ----- Create queries -----

    // query will take in account datatables search, order and paging
    // criterias
    JPAQuery query = newJPAQuery(entityManager);
    query = query.from(entity);

    // baseQuery will use base search values only in order to count
    // all for success paging
    JPAQuery baseQuery = newJPAQuery(entityManager);
    baseQuery = baseQuery.from(entity);

    // ----- Entity associations for Query JOINs, ORDER BY, ... -----

    Map<String, PathBuilder<?>> associationMap = new HashMap<String, PathBuilder<?>>();

    query = prepareQueryAssociationMap(entity, filterByAssociations, datatablesCriterias, findInAllColumns,
            query, associationMap);

    // ----- Query WHERE clauses -----

    // Filters by column. Using BooleanBuilder, a cascading builder for
    // Predicate expressions
    BooleanBuilder filtersByColumnPredicate = new BooleanBuilder();

    // Filters by table (for all columns)
    BooleanBuilder filtersByTablePredicate = new BooleanBuilder();

    try {

        // Build the filters by column expression
        if (datatablesCriterias.hasOneFilteredColumn()) {

            filtersByColumnPredicate = prepareQueryFilterPart(entity, filterByAssociations, datatablesCriterias,
                    associationMap, filtersByColumnPredicate);
        }

        // Build the query to search the given value in all columns
        filtersByTablePredicate = prepareQuerySearchPart(entity, filterByAssociations, datatablesCriterias,
                findInAllColumns, associationMap, filtersByTablePredicate);
    } catch (Exception e) {
        LOGGER.error("Exception preparing filter for entity {}", entity.getType(), e);
        SearchResults<T> searchResults = new SearchResults<T>(new ArrayList<T>(0), 0, isPaged,
                new Long(org.apache.commons.lang3.ObjectUtils
                        .defaultIfNull(datatablesCriterias.getDisplayStart(), 0)),
                new Long(org.apache.commons.lang3.ObjectUtils
                        .defaultIfNull(datatablesCriterias.getDisplaySize(), 0)),
                0);
        return searchResults;
    }

    // ----- Query ORDER BY -----

    List<OrderSpecifier<?>> orderSpecifiersList = prepareQueryOrder(entity, orderByAssociations,
            datatablesCriterias, associationMap);

    // ----- Query results paging -----

    Long offset = null;
    Long limit = null;

    if (isPaged) {
        limit = new Long(datatablesCriterias.getDisplaySize());
    }
    if (datatablesCriterias.getDisplayStart() != null && datatablesCriterias.getDisplayStart() >= 0) {
        offset = new Long(datatablesCriterias.getDisplayStart());
    }

    // ------- manage Rows-on-top ----

    List<T> firstRows = null;

    // Decrease limits if firstRowsIds is used
    if (rowsOnTopIds != null) {
        LOGGER.trace("Prepare rows on top: {}", rowsOnTopIds);

        // Coherce row-on-top ids types
        Object[] cohercedRowsOnTopId = new Object[rowsOnTopIds.length];

        EntityType<? extends T> entityMetamodel = entityManager.getMetamodel().entity(entity.getType());
        // We always have just one id. This id can be an Embedded Id
        Class<?> idType = entityMetamodel.getIdType().getJavaType();
        @SuppressWarnings("unchecked")
        SingularAttribute<? extends T, ?> idAttr = (SingularAttribute<? extends T, ?>) entityMetamodel
                .getId(idType);

        Object curId;
        for (int i = 0; i < rowsOnTopIds.length; i++) {
            curId = rowsOnTopIds[i];
            if (curId.getClass() != idType) {
                cohercedRowsOnTopId[i] = conversionService.convert(curId, idType);
            } else {
                cohercedRowsOnTopId[i] = curId;
            }
        }

        // Create expression for rows-on-top
        BooleanExpression firstRowsInExpression = querydslUtilsBean.createCollectionExpression(entity,
                idAttr.getName(), Arrays.asList(cohercedRowsOnTopId));

        LOGGER.trace("Expression for rowsOnTop: {}", firstRowsInExpression);

        // Exclude firstRows from base query
        basePredicate = basePredicate.and(firstRowsInExpression.not());

        LOGGER.trace("basePredicate to exclude rowsOnTop now is: {}", basePredicate);

        // Gets rows on top
        JPAQuery firstRowsQuery = newJPAQuery(entityManager);
        firstRowsQuery = firstRowsQuery.from(entity).where(firstRowsInExpression);

        LOGGER.trace("rowsOnTop query is: {}", firstRowsQuery);

        try {
            // TODO handle fieldSelector
            firstRows = firstRowsQuery.list(entity);
        } catch (PersistenceException exSql) {
            // Log query
            LOGGER.error("Error excecuting SQL for firstRow (sql = '{}' )", firstRowsQuery);
            throw exSql;
        }

        LOGGER.trace("Found {} rows for rowsOnTop", firstRows.size());
        // Adjust limit with rows-on-top found
        if (limit != null) {
            LOGGER.trace("Update main query limit: {} --> {}", limit, limit - firstRows.size());
            limit = limit - firstRows.size();
        }

    }

    // ----- Execute the query -----
    List<T> elements = null;

    // Compose the final query and update query var to be used to count
    // total amount of rows if needed

    if (distinct) {
        LOGGER.trace("Use distinct query!!!");
        query = query.distinct();
    }

    // Predicate for base query
    boolean hasBasePredicate = true;
    if (basePredicate == null) {
        basePredicate = new BooleanBuilder();
        hasBasePredicate = false;
    }

    // query projection to count all entities without paging
    baseQuery.where(basePredicate);

    // query projection to be used to get the results and to count filtered
    // results
    query = query.where(
            basePredicate.and(filtersByColumnPredicate.getValue()).and(filtersByTablePredicate.getValue()));

    // Calculate the total amount of rows taking in account datatables
    // search and paging criterias. When results are paginated we
    // must execute a count query, otherwise the size of matched rows List
    // is the total amount of rows
    long totalResultCount = 0;
    if (isPaged) {
        try {
            totalResultCount = query.count();
        } catch (PersistenceException exSql) {
            // Log query
            LOGGER.error("Error excecuting 'count' SQL: {}", query);
            throw exSql;
        }
    }

    if (offset == null) {
        offset = new Long(0);
    } else if (offset > totalResultCount) {
        // If offset value is bigger than total results,
        // offset needs start on 0
        offset = new Long(0);
    }

    // QueryModifiers combines limit and offset
    QueryModifiers queryModifiers = new QueryModifiers(limit, offset);
    LOGGER.trace("Set limit={} offset={}", limit, offset);

    // List ordered and paginated results. An empty list is returned for no
    // results.
    query = query.orderBy(orderSpecifiersList.toArray(new OrderSpecifier[orderSpecifiersList.size()]));

    LOGGER.debug("Execute query: {}", query);
    try {
        elements = query.restrict(queryModifiers).list(entity);
    } catch (PersistenceException exSql) {
        // Log query
        LOGGER.error("Error excecuting SQL: {}", query);
        throw exSql;
    }

    if (!isPaged) {
        totalResultCount = elements.size();
    }

    long totalBaseCount = totalResultCount;
    if (hasBasePredicate) {
        // Calculate the total amount of entities including base filters
        // only
        LOGGER.trace("Execute count query: {}", baseQuery);
        try {
            totalBaseCount = baseQuery.count();
        } catch (PersistenceException exSql) {
            // Log query
            LOGGER.error("Error excecuting 'count' SQL: {}", baseQuery);
            throw exSql;
        }
        LOGGER.trace("Found : {}", totalBaseCount);
    }

    if (firstRows != null) {
        // Adjust result with rows-on-top
        totalResultCount = totalResultCount + firstRows.size();
        totalBaseCount = totalBaseCount + firstRows.size();
        elements.addAll(0, firstRows);
    }

    // Create a new SearchResults instance
    if (limit == null) {
        limit = totalBaseCount;
    }
    SearchResults<T> searchResults = new SearchResults<T>(elements, totalResultCount, isPaged, offset, limit,
            totalBaseCount);

    LOGGER.debug("findByCriteria: return {} rows from {} (offset={} limit={})", totalResultCount,
            totalBaseCount, offset, limit);
    return searchResults;
}

From source file:org.querybyexample.jpa.ByExampleUtil.java

/**
 * Invoke byExample method for each not null x-to-one association when their pk is not set. This allows you to search entities based on an associated
 * entity's properties value.//from  w  w w  .j  a v  a 2s.c o m
 */
@SuppressWarnings("unchecked")
public <T extends Identifiable<?>, M2O extends Identifiable<?>> List<Predicate> byExampleOnXToOne(
        ManagedType<T> mt, Root<T> mtPath, T mtValue, SearchParameters sp, CriteriaBuilder builder) {
    List<Predicate> predicates = newArrayList();
    for (SingularAttribute<? super T, ?> attr : mt.getSingularAttributes()) {
        if (attr.getPersistentAttributeType() == MANY_TO_ONE
                || attr.getPersistentAttributeType() == ONE_TO_ONE) {
            M2O m2oValue = (M2O) JpaUtil.getValue(mtValue, mt.getAttribute(attr.getName()));
            Class<M2O> m2oType = (Class<M2O>) attr.getBindableJavaType();
            Path<M2O> m2oPath = (Path<M2O>) mtPath.get(attr);
            ManagedType<M2O> m2oMt = em.getMetamodel().entity(m2oType);
            if (m2oValue != null) {
                if (m2oValue.isIdSet()) { // we have an id, let's restrict only on this field
                    predicates.add(builder.equal(m2oPath.get("id"), m2oValue.getId()));
                } else {
                    predicates.addAll(byExample(m2oMt, m2oPath, m2oValue, sp, builder));
                }
            }
        }
    }
    return predicates;
}