com.mysema.query.types.Predicate Java Examples

The following examples show how to use com.mysema.query.types.Predicate. 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: DepartmentService.java    From spring-boot-practice with Apache License 2.0 6 votes vote down vote up
public Page<Department> findAll(Pageable pageable) {
    Predicate predicate = null; // TODO

    SDepartment department = SDepartment.department;
    SEmployee employee = SEmployee.employee;

    PathBuilder<Department> builder = new PathBuilder<>(Department.class, department.getMetadata());
    QuerydslSQL querydsl = new QuerydslSQL(builder);

    JPASQLQuery query = querydsl.applyPagination(pageable, createQuery(predicate));
    Long total = createBaseQuery(predicate).count();

    List<Department> content =
        query.orderBy(department.id.asc()).list(
            Projections.constructor(
                Department.class,
                department.id,
                department.name,
                // SQLExpressions.groupConcat() is not available in Querydsl 3.6.7
                sqlTemplatesService.groupConcat(employee.name, employee.id.asc())
            ));

    return new PageImpl<>(content, pageable, total);
}
 
Example #2
Source File: PermissionService.java    From spring-boot-practice with Apache License 2.0 6 votes vote down vote up
public Page<Permission> findAllByRoleId(Integer id, Pageable pageable) {
    QRole role = QRole.role;
    Predicate predicate = role.id.eq(id);

    PathBuilder<Permission> builder = new PathBuilder<Permission>(Permission.class, QPermission.permission.getMetadata());
    Querydsl querydsl = new Querydsl(em, builder);

    JPQLQuery countQuery = createQuery(predicate);
    JPQLQuery query = querydsl.applyPagination(pageable, createQuery(predicate));

    Path<Permission> path = QPermission.permission;
    Long total = countQuery.count();
    List<Permission> content = total > pageable.getOffset() ? query.list(path) : Collections.<Permission>emptyList();

    return new PageImpl<Permission>(content, pageable, total);
}
 
Example #3
Source File: PermissionService.java    From spring-boot-practice with Apache License 2.0 6 votes vote down vote up
public Page<Permission> findAllByRoleId(Integer id, Pageable pageable) {
    QRole role = QRole.role;
    Predicate predicate = role.id.eq(id);

    PathBuilder<Permission> builder = new PathBuilder<Permission>(Permission.class, QPermission.permission.getMetadata());
    Querydsl querydsl = new Querydsl(em, builder);

    JPQLQuery countQuery = createQuery(predicate);
    JPQLQuery query = querydsl.applyPagination(pageable, createQuery(predicate));

    Path<Permission> path = QPermission.permission;
    Long total = countQuery.count();
    List<Permission> content = total > pageable.getOffset() ? query.list(path) : Collections.<Permission>emptyList();

    return new PageImpl<Permission>(content, pageable, total);
}
 
Example #4
Source File: QuerydslUtilsBeanGeoImpl.java    From gvnix with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Method to create Bounding box intersects expression
 * 
 * @param entityPath
 * @param boundingBox
 * @param fieldName
 * @return
 */
public static <T> Predicate createIntersectsExpression(
        PathBuilder<T> entityPath, String fieldName, Geometry boundingBox) {
    JTSPolygonPath<Polygon> polygonPath = new JTSPolygonPath<Polygon>(
            entityPath, fieldName);
    BooleanExpression intersectsExpression = polygonPath
            .intersects(boundingBox);
    return intersectsExpression;
}
 
Example #5
Source File: PermissionService.java    From spring-boot-practice with Apache License 2.0 5 votes vote down vote up
public JPAQuery createQuery(Predicate predicate) {
    QPermission permission = QPermission.permission;
    QRolePermission rolePermission = QRolePermission.rolePermission;
    QRole role = QRole.role;
    BooleanBuilder builder = new BooleanBuilder();
    builder.and(predicate);
    builder.and(permission.deletedAt.isNull());
    builder.and(rolePermission.deletedAt.isNull());
    builder.and(role.deletedAt.isNull());
    return new JPAQuery(em)
        .from(permission)
        .leftJoin(permission.rolePermission, rolePermission)
        .leftJoin(rolePermission.role, role)
        .where(builder);
}
 
Example #6
Source File: AService.java    From spring-boot-practice with Apache License 2.0 5 votes vote down vote up
/**
 * <pre>{@code
 * select *
 * from a
 * join b on b.a_id = a.id
 * join c on c.b_id = b.id
 * left join d on c.d_id = d.id
 * left join (select * from e where sub_id = 1) as e1 on e1.d_id = d.id
 * left join (select * from e where sub_id = 2) as e2 on e2.d_id = d.id
 * left join (select * from e where sub_id = 3) as e3 on e3.d_id = d.id
 * }</pre>
 */
private JPASQLQuery createQuery(Predicate predicate) {
    SA a = SA.a;
    SB b = SB.b;
    SC c = SC.c;
    SD d = SD.d;
    SE e = SE.e;

    // Alias
    SE e1 = new SE("E1");
    SE e2 = new SE("E2");
    SE e3 = new SE("E3");

    JPASQLQuery query = new JPASQLQuery(em, sqlTemplatesService.getTemplates())
        .from(a)
        .join(b).on(b.aId.eq(a.id))
        .join(c).on(c.bId.eq(b.id))
        .leftJoin(d).on(c.dId.eq(d.id))
        // Sub-queries can be used in left join
        .leftJoin(new SQLSubQuery().from(e).where(e.subId.eq(1)).list(e.all()), e1).on(e1.dId.eq(d.id))
        .leftJoin(new SQLSubQuery().from(e).where(e.subId.eq(2)).list(e.all()), e2).on(e2.dId.eq(d.id))
        .leftJoin(new SQLSubQuery().from(e).where(e.subId.eq(3)).list(e.all()), e3).on(e3.dId.eq(d.id));
    if (predicate != null) {
        query.where(predicate);
    }
    return query;
}
 
Example #7
Source File: AService.java    From spring-boot-practice with Apache License 2.0 5 votes vote down vote up
public Page<Tuple> findAllAsTuple(Pageable pageable) {
    Predicate predicate = null; // TODO

    SA a = SA.a;
    SB b = SB.b;
    SC c = SC.c;
    SD d = SD.d;
    SE e1 = new SE("E1");
    SE e2 = new SE("E2");
    SE e3 = new SE("E3");

    PathBuilder<A> builder = new PathBuilder<>(A.class, a.getMetadata());
    QuerydslSQL querydsl = new QuerydslSQL(builder);

    JPASQLQuery query = querydsl.applyPagination(pageable, createQuery(predicate));
    Long total = createQuery(predicate).count();

    List<Tuple> content =
        query.orderBy(a.id.asc()).list(
            a.id,
            a.name,
            b.name,
            c.name,
            d.name,
            e1.name,
            e2.name,
            e3.name
        );

    return new PageImpl<>(content, pageable, total);
}
 
Example #8
Source File: AService.java    From spring-boot-practice with Apache License 2.0 5 votes vote down vote up
public Page<ExtendedA> findAll(Pageable pageable) {
    Predicate predicate = null; // TODO

    SA a = SA.a;
    SB b = SB.b;
    SC c = SC.c;
    SD d = SD.d;
    SE e1 = new SE("E1");
    SE e2 = new SE("E2");
    SE e3 = new SE("E3");

    PathBuilder<A> builder = new PathBuilder<>(A.class, a.getMetadata());
    QuerydslSQL querydsl = new QuerydslSQL(builder);

    JPASQLQuery query = querydsl.applyPagination(pageable, createQuery(predicate));
    Long total = createQuery(predicate).count();

    List<ExtendedA> content =
        query.orderBy(a.id.asc()).list(
            Projections.constructor(
                ExtendedA.class,
                a.id,
                a.name,
                b.name,
                c.name,
                d.name,
                e1.name,
                e2.name,
                e3.name
            ));

    return new PageImpl<>(content, pageable, total);
}
 
Example #9
Source File: PermissionService.java    From spring-boot-practice with Apache License 2.0 5 votes vote down vote up
public JPAQuery createQuery(Predicate predicate) {
    QPermission permission = QPermission.permission;
    QRolePermission rolePermission = QRolePermission.rolePermission;
    QRole role = QRole.role;
    return new JPAQuery(em)
        .from(permission)
        .leftJoin(permission.rolePermission, rolePermission)
        .leftJoin(rolePermission.role, role)
        .where(predicate);
}
 
Example #10
Source File: DepartmentService.java    From spring-boot-practice with Apache License 2.0 5 votes vote down vote up
private JPASQLQuery createBaseQuery(Predicate predicate) {
    SDepartment department = SDepartment.department;
    JPASQLQuery query = new JPASQLQuery(entityManager, sqlTemplatesService.getTemplates()).from(department);
    if (predicate != null) {
        query.where(predicate);
    }
    return query;
}
 
Example #11
Source File: DepartmentService.java    From spring-boot-practice with Apache License 2.0 5 votes vote down vote up
private JPASQLQuery createQuery(Predicate predicate) {
    SDepartment department = SDepartment.department;
    SEmployee employee = SEmployee.employee;
    JPASQLQuery query = createBaseQuery(predicate)
        .leftJoin(employee).on(employee.departmentId.eq(department.id))
        .groupBy(department.id);
    if (predicate != null) {
        query.where(predicate);
    }
    return query;
}
 
Example #12
Source File: QuerydslUtils.java    From gvnix with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Utility for constructing where clause expressions.
 * 
 * @param entityPath Full path to entity and associations. For example:
 *        {@code Pet} , {@code Pet.owner}
 * @param fieldName Property name in the given entity path. For example:
 *        {@code name} in {@code Pet} entity, {@code firstName} in
 *        {@code Pet.owner} entity.
 * @param fieldType Property value {@code Class}
 * @param searchStr the value to find, may be null
 * @return Predicate
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public static <T> Predicate createExpression(PathBuilder<T> entityPath,
        String fieldName, String searchStr,
        ConversionService conversionService) {

    TypeDescriptor descriptor = getTypeDescriptor(fieldName, entityPath);
    if (descriptor == null) {
        throw new IllegalArgumentException(String.format(
                "Can't found field '%s' on entity '%s'", fieldName,
                entityPath.getType()));
    }
    Class<?> fieldType = descriptor.getType();

    // Check for field type in order to delegate in custom-by-type
    // create expression method
    if (String.class == fieldType) {
        return createStringLikeExpression(entityPath, fieldName, searchStr);
    }
    else if (Boolean.class == fieldType || boolean.class == fieldType) {
        return createBooleanExpression(entityPath, fieldName, searchStr);
    }
    else if (Number.class.isAssignableFrom(fieldType)
            || NUMBER_PRIMITIVES.contains(fieldType)) {
        return createNumberExpressionGenerics(entityPath, fieldName,
                fieldType, descriptor, searchStr, conversionService);
    }
    else if (Date.class.isAssignableFrom(fieldType)
            || Calendar.class.isAssignableFrom(fieldType)) {
        BooleanExpression expression = createDateExpression(entityPath,
                fieldName, (Class<Date>) fieldType, searchStr);
        return expression;
    }

    else if (fieldType.isEnum()) {
        return createEnumExpression(entityPath, fieldName, searchStr,
                (Class<? extends Enum>) fieldType);
    }
    return null;
}
 
Example #13
Source File: DefaultPredicateArgumentResolver.java    From java-platform with Apache License 2.0 5 votes vote down vote up
@Override
public boolean supportsParameter(MethodParameter parameter) {

	if (Predicate.class.equals(parameter.getParameterType())) {
		return true;
	}

	if (parameter.hasParameterAnnotation(QuerydslPredicate.class)) {
		throw new IllegalArgumentException(
				String.format("Parameter at position %s must be of type Predicate but was %s.",
						parameter.getParameterIndex(), parameter.getParameterType()));
	}

	return false;
}
 
Example #14
Source File: QuerydslUtilsBeanImpl.java    From gvnix with GNU General Public License v3.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public <T> Predicate createFilterExpression(PathBuilder<T> entityPath,
        String fieldName, Class<?> fieldType, String searchStr) {

    return createFilterExpression(entityPath, fieldName, searchStr);

}
 
Example #15
Source File: QuerydslUtilsBeanImpl.java    From gvnix with GNU General Public License v3.0 5 votes vote down vote up
@Override
public <T> Predicate createSearchExpression(PathBuilder<T> entityPath,
        String fieldName, String searchStr) {

    TypeDescriptor descriptor = getTypeDescriptor(fieldName, entityPath);
    if (descriptor == null) {
        throw new IllegalArgumentException(String.format(
                "Can't found field '%s' on entity '%s'", fieldName,
                entityPath.getType()));
    }
    Class<?> fieldType = descriptor.getType();

    // Check for field type in order to delegate in custom-by-type
    // create expression method
    if (String.class == fieldType) {
        return createStringLikeExpression(entityPath, fieldName, searchStr);
    }
    else if (Boolean.class == fieldType || boolean.class == fieldType) {
        return createBooleanExpression(entityPath, fieldName, searchStr);
    }
    else if (Number.class.isAssignableFrom(fieldType)
            || NUMBER_PRIMITIVES.contains(fieldType)) {
        return createNumberExpressionGenerics(entityPath, fieldName,
                fieldType, descriptor, searchStr);
    }
    else if (Date.class.isAssignableFrom(fieldType)
            || Calendar.class.isAssignableFrom(fieldType)) {
        BooleanExpression expression = createDateExpression(entityPath,
                fieldName, (Class<Date>) fieldType, searchStr);
        return expression;
    }

    else if (fieldType.isEnum()) {
        return createEnumExpression(entityPath, fieldName, searchStr,
                (Class<? extends Enum>) fieldType);
    }
    return null;
}
 
Example #16
Source File: QuerydslUtils.java    From gvnix with GNU General Public License v3.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
public static <T> Predicate createNumberExpressionGenerics(
        PathBuilder<T> entityPath, String fieldName, Class<?> fieldType,
        TypeDescriptor descriptor, String searchStr,
        ConversionService conversionService) {
    Predicate numberExpression = null;

    if (isNumber(searchStr, conversionService, descriptor)) {
        if (BigDecimal.class.isAssignableFrom(fieldType)) {
            numberExpression = createNumberExpression(entityPath,
                    fieldName, (Class<BigDecimal>) fieldType, descriptor,
                    searchStr, conversionService);
        }
        if (BigInteger.class.isAssignableFrom(fieldType)) {
            numberExpression = createNumberExpression(entityPath,
                    fieldName, (Class<BigInteger>) fieldType, descriptor,
                    searchStr, conversionService);
        }
        if (Byte.class.isAssignableFrom(fieldType)) {
            numberExpression = createNumberExpression(entityPath,
                    fieldName, (Class<Byte>) fieldType, descriptor,
                    searchStr, conversionService);
        }
        if (Double.class.isAssignableFrom(fieldType)
                || double.class == fieldType) {
            numberExpression = createNumberExpression(entityPath,
                    fieldName, (Class<Double>) fieldType, descriptor,
                    searchStr, conversionService);
        }
        if (Float.class.isAssignableFrom(fieldType)
                || float.class == fieldType) {
            numberExpression = createNumberExpression(entityPath,
                    fieldName, (Class<Float>) fieldType, descriptor,
                    searchStr, conversionService);
        }
        if (Integer.class.isAssignableFrom(fieldType)
                || int.class == fieldType) {
            numberExpression = createNumberExpression(entityPath,
                    fieldName, (Class<Integer>) fieldType, descriptor,
                    searchStr, conversionService);
        }
        if (Long.class.isAssignableFrom(fieldType)
                || long.class == fieldType) {
            numberExpression = createNumberExpression(entityPath,
                    fieldName, (Class<Long>) fieldType, descriptor,
                    searchStr, conversionService);
        }
        if (Short.class.isAssignableFrom(fieldType)
                || short.class == fieldType) {
            numberExpression = createNumberExpression(entityPath,
                    fieldName, (Class<Short>) fieldType, descriptor,
                    searchStr, conversionService);
        }
    }
    return numberExpression;
}
 
Example #17
Source File: QuerydslUtils.java    From gvnix with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Utility for constructing where clause expressions.
 * 
 * @param entityPath Full path to entity and associations. For example:
 *        {@code Pet} , {@code Pet.owner}
 * @param fieldName Property name in the given entity path. For example:
 *        {@code name} in {@code Pet} entity, {@code firstName} in
 *        {@code Pet.owner} entity.
 * @param fieldType Property value {@code Class}
 * @param searchStr the value to find, may be null
 * @return Predicate
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public static <T> Predicate createExpression(PathBuilder<T> entityPath,
        String fieldName, String searchStr,
        ConversionService conversionService, MessageSource messageSource) {

    TypeDescriptor descriptor = getTypeDescriptor(fieldName, entityPath);
    if (descriptor == null) {
        throw new IllegalArgumentException(String.format(
                "Can't found field '%s' on entity '%s'", fieldName,
                entityPath.getType()));
    }
    Class<?> fieldType = descriptor.getType();

    // Check for field type in order to delegate in custom-by-type
    // create expression method
    if (String.class == fieldType) {
        return createStringExpressionWithOperators(entityPath, fieldName,
                searchStr, conversionService, messageSource);
    }
    else if (Boolean.class == fieldType || boolean.class == fieldType) {
        return createBooleanExpressionWithOperators(entityPath, fieldName,
                searchStr, conversionService, messageSource);
    }
    else if (Number.class.isAssignableFrom(fieldType)
            || NUMBER_PRIMITIVES.contains(fieldType)) {
        return createNumberExpressionGenericsWithOperators(entityPath,
                fieldName, descriptor, searchStr, conversionService,
                messageSource);
    }
    else if (Date.class.isAssignableFrom(fieldType)
            || Calendar.class.isAssignableFrom(fieldType)) {
        String datePattern = "dd/MM/yyyy";
        if (messageSource != null) {
            datePattern = messageSource.getMessage(
                    "global.filters.operations.date.pattern", null,
                    LocaleContextHolder.getLocale());
        }
        BooleanExpression expression = createDateExpressionWithOperators(
                entityPath, fieldName, (Class<Date>) fieldType, searchStr,
                conversionService, messageSource, datePattern);
        return expression;
    }

    else if (fieldType.isEnum()) {
        return createEnumExpression(entityPath, fieldName, searchStr,
                (Class<? extends Enum>) fieldType);
    }
    return null;
}
 
Example #18
Source File: DatatablesUtils.java    From gvnix with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Prepare search part for a query of findByCriteria
 * 
 * @param entity
 * @param filterByAssociations
 * @param datatablesCriterias
 * @param findInAllColumns
 * @param associationMap
 * @param filtersByTablePredicate
 * @return
 */
private static <T> BooleanBuilder prepareQuerySearchPart(
        PathBuilder<T> entity,
        Map<String, List<String>> filterByAssociations,
        DatatablesCriterias datatablesCriterias, boolean findInAllColumns,
        Map<String, PathBuilder<?>> associationMap,
        BooleanBuilder filtersByTablePredicate,
        ConversionService conversionService) {
    String searchStr = datatablesCriterias.getSearch();
    if (StringUtils.isEmpty(searchStr)) {
        // Nothing to do
        return filtersByTablePredicate;
    }
    LOGGER.debug(
            "Preparing search expression for '{}' string on entity {}...",
            searchStr, entity.getType());
    if (findInAllColumns) {
        boolean expressionExists = false;
        // Add filterable columns only
        for (ColumnDef column : datatablesCriterias.getColumnDefs()) {
            if (column.isFilterable()) {

                // Entity field name and type
                String fieldName = unescapeDot(column.getName());
                LOGGER.trace("Check expression column {}...", fieldName);

                // Find in all columns means we want to find given
                // value in at least one entity property, so we must
                // join the where clauses by OR
                Predicate expression = QuerydslUtils.createExpression(
                        entity, fieldName, searchStr, conversionService);
                if (expression != null) {
                    filtersByTablePredicate = filtersByTablePredicate
                            .or(expression);
                    LOGGER.trace("Added expression {}", expression);
                    expressionExists = true;
                }

                // If column is an association and there are given
                // join attributes, add those attributes to WHERE
                // predicates
                List<String> attributes = filterByAssociations
                        .get(fieldName);
                if (attributes != null && attributes.size() > 0) {
                    PathBuilder<?> associationPath = associationMap
                            .get(fieldName);
                    List<String> associationFields = filterByAssociations
                            .get(fieldName);

                    for (String associationFieldName : associationFields) {

                        expression = QuerydslUtils.createExpression(
                                associationPath, associationFieldName,
                                searchStr, conversionService);
                        filtersByTablePredicate = filtersByTablePredicate
                                .or(expression);

                        LOGGER.trace(
                                "Added expression (by association) {}",
                                expression);
                    }
                }
            }
        }
        // If expression is null returns error to returns an empty
        // DataSource
        if (!expressionExists) {
            throw new RuntimeException("Expression cannot be null");
        }
    }
    LOGGER.debug("Search expression: {}", filtersByTablePredicate);
    return filtersByTablePredicate;
}
 
Example #19
Source File: DatatablesUtils.java    From gvnix with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Prepares filter part for a query of findByCriteria
 * 
 * @param entity
 * @param filterByAssociations
 * @param datatablesCriterias
 * @param associationMap
 * @param filtersByColumnPredicate
 * @return
 */
private static <T> BooleanBuilder prepareQueryFilterPart(
        PathBuilder<T> entity,
        Map<String, List<String>> filterByAssociations,
        DatatablesCriterias datatablesCriterias,
        Map<String, PathBuilder<?>> associationMap,
        BooleanBuilder filtersByColumnPredicate,
        ConversionService conversionService, MessageSource messageSource) {
    // Add filterable columns only

    LOGGER.debug("Preparing filter-column expression for entity {}...",
            entity.getType());

    Predicate filterExpression;

    for (ColumnDef column : datatablesCriterias.getColumnDefs()) {

        // Each column has its own search by value
        String searchStr = column.getSearch();

        // true if the search must include this column
        boolean findInColumn = column.isFilterable()
                && StringUtils.isNotEmpty(searchStr);

        if (findInColumn) {

            // Entity field name and type
            String fieldName = unescapeDot(column.getName());

            LOGGER.trace("Preparing filter for '{}' by '{}'...", fieldName,
                    searchStr);

            // On column search, connect where clauses together by
            // AND
            // because we want found the records which columns
            // match with column filters
            filterExpression = QuerydslUtils.createExpression(entity,
                    fieldName, searchStr, conversionService, messageSource);

            filtersByColumnPredicate = filtersByColumnPredicate
                    .and(filterExpression);

            LOGGER.trace("filtersByColumnPredicate AND '{}'",
                    filterExpression);

            // TODO: Este codigo se puede pasar a QuerydslUtils ?

            // If column is an association and there are given
            // join attributes, add those attributes to WHERE
            // predicates
            List<String> attributes = filterByAssociations.get(fieldName);
            if (attributes != null && attributes.size() > 0) {

                // Filters of associated entity properties
                BooleanBuilder filtersByAssociationPredicate = new BooleanBuilder();

                PathBuilder<?> associationPath = associationMap
                        .get(fieldName);
                List<String> associationFields = filterByAssociations
                        .get(fieldName);

                for (String associationFieldName : associationFields) {

                    // On association search, connect
                    // associated entity where clauses by OR
                    // because all assoc entity properties are
                    // inside the same column and any of its
                    // property value can match with given search
                    // value
                    filterExpression = QuerydslUtils.createExpression(
                            associationPath, associationFieldName,
                            searchStr, conversionService);
                    filtersByAssociationPredicate = filtersByAssociationPredicate
                            .or(filterExpression);

                    LOGGER.trace("filtersByAssociationPredicate OR '{}'",
                            filterExpression);
                }

                filtersByColumnPredicate = filtersByColumnPredicate
                        .and(filtersByAssociationPredicate.getValue());

                LOGGER.trace("filtersByColumnPredicate AND '{}'",
                        filtersByAssociationPredicate.getValue());
            }
        }
    }

    LOGGER.debug("Final filtersByColumnPredicate  =  '{}'",
            filtersByColumnPredicate);
    return filtersByColumnPredicate;
}
 
Example #20
Source File: QuerydslUtilsBeanImpl.java    From gvnix with GNU General Public License v3.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
public <T> Predicate createFilterExpression(PathBuilder<T> entityPath,
        String fieldName, String searchStr) {
    TypeDescriptor descriptor = getTypeDescriptor(fieldName, entityPath);
    if (descriptor == null) {
        throw new IllegalArgumentException(String.format(
                "Can't found field '%s' on entity '%s'", fieldName,
                entityPath.getType()));
    }
    Class<?> fieldType = descriptor.getType();

    // Check for field type in order to delegate in custom-by-type
    // create expression method
    if (String.class == fieldType) {
        return createStringExpressionWithOperators(entityPath, fieldName,
                searchStr);
    }
    else if (Boolean.class == fieldType || boolean.class == fieldType) {
        return createBooleanExpressionWithOperators(entityPath, fieldName,
                searchStr);
    }
    else if (Number.class.isAssignableFrom(fieldType)
            || NUMBER_PRIMITIVES.contains(fieldType)) {
        return createNumberExpressionGenericsWithOperators(entityPath,
                fieldName, descriptor, searchStr);
    }
    else if (Date.class.isAssignableFrom(fieldType)
            || Calendar.class.isAssignableFrom(fieldType)) {
        String datePattern = "dd/MM/yyyy";
        if (messageSource != null) {
            datePattern = messageSource.getMessage(
                    "global.filters.operations.date.pattern", null,
                    LocaleContextHolder.getLocale());
        }
        BooleanExpression expression = createDateExpressionWithOperators(
                entityPath, fieldName, (Class<Date>) fieldType, searchStr,
                datePattern);
        return expression;
    }

    else if (fieldType.isEnum()) {
        return createEnumExpression(entityPath, fieldName, searchStr,
                (Class<? extends Enum>) fieldType);
    }
    return null;
}
 
Example #21
Source File: QuerydslUtilsBeanImpl.java    From gvnix with GNU General Public License v3.0 4 votes vote down vote up
@Override
public <T> Predicate createSearchExpression(PathBuilder<T> entityPath,
        String fieldName, Class<?> fieldType, String searchStr) {
    return createSearchExpression(entityPath, fieldName, searchStr);
}
 
Example #22
Source File: QuerydslUtilsBeanImpl.java    From gvnix with GNU General Public License v3.0 4 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public <T> Predicate createNumberExpressionGenerics(
        PathBuilder<T> entityPath, String fieldName, Class<?> fieldType,
        TypeDescriptor descriptor, String searchStr) {
    Predicate numberExpression = null;

    if (isNumber(searchStr, descriptor)) {
        if (BigDecimal.class.isAssignableFrom(fieldType)) {
            numberExpression = createNumberExpression(entityPath,
                    fieldName, (Class<BigDecimal>) fieldType, descriptor,
                    searchStr);
        }
        if (BigInteger.class.isAssignableFrom(fieldType)) {
            numberExpression = createNumberExpression(entityPath,
                    fieldName, (Class<BigInteger>) fieldType, descriptor,
                    searchStr);
        }
        if (Byte.class.isAssignableFrom(fieldType)) {
            numberExpression = createNumberExpression(entityPath,
                    fieldName, (Class<Byte>) fieldType, descriptor,
                    searchStr);
        }
        if (Double.class.isAssignableFrom(fieldType)
                || double.class == fieldType) {
            numberExpression = createNumberExpression(entityPath,
                    fieldName, (Class<Double>) fieldType, descriptor,
                    searchStr);
        }
        if (Float.class.isAssignableFrom(fieldType)
                || float.class == fieldType) {
            numberExpression = createNumberExpression(entityPath,
                    fieldName, (Class<Float>) fieldType, descriptor,
                    searchStr);
        }
        if (Integer.class.isAssignableFrom(fieldType)
                || int.class == fieldType) {
            numberExpression = createNumberExpression(entityPath,
                    fieldName, (Class<Integer>) fieldType, descriptor,
                    searchStr);
        }
        if (Long.class.isAssignableFrom(fieldType)
                || long.class == fieldType) {
            numberExpression = createNumberExpression(entityPath,
                    fieldName, (Class<Long>) fieldType, descriptor,
                    searchStr);
        }
        if (Short.class.isAssignableFrom(fieldType)
                || short.class == fieldType) {
            numberExpression = createNumberExpression(entityPath,
                    fieldName, (Class<Short>) fieldType, descriptor,
                    searchStr);
        }
    }
    return numberExpression;
}
 
Example #23
Source File: DatatablesUtilsBeanImpl.java    From gvnix with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Prepares filter part for a query of findByCriteria
 * 
 * @param entity
 * @param filterByAssociations
 * @param datatablesCriterias
 * @param associationMap
 * @param filtersByColumnPredicate
 * @return
 */
private <T> BooleanBuilder prepareQueryFilterPart(PathBuilder<T> entity,
        Map<String, List<String>> filterByAssociations,
        DatatablesCriterias datatablesCriterias,
        Map<String, PathBuilder<?>> associationMap,
        BooleanBuilder filtersByColumnPredicate) {
    // Add filterable columns only

    LOGGER.debug("Preparing filter-column expression for entity {}...",
            entity.getType());

    Predicate filterExpression;

    for (ColumnDef column : datatablesCriterias.getColumnDefs()) {

        // Each column has its own search by value
        String searchStr = column.getSearch();

        // true if the search must include this column
        boolean findInColumn = column.isFilterable()
                && StringUtils.isNotEmpty(searchStr);

        if (findInColumn) {

            // Entity field name and type
            String fieldName = unescapeDot(column.getName());

            LOGGER.trace("Preparing filter for '{}' by '{}'...", fieldName,
                    searchStr);

            // On column search, connect where clauses together by
            // AND
            // because we want found the records which columns
            // match with column filters
            filterExpression = querydslUtilsBean.createFilterExpression(
                    entity, fieldName, searchStr);

            filtersByColumnPredicate = filtersByColumnPredicate
                    .and(filterExpression);

            LOGGER.trace("filtersByColumnPredicate AND '{}'",
                    filterExpression);

            // TODO: Este codigo se puede pasar a QuerydslUtils ?

            // If column is an association and there are given
            // join attributes, add those attributes to WHERE
            // predicates
            List<String> attributes = filterByAssociations.get(fieldName);
            if (attributes != null && attributes.size() > 0) {

                // Filters of associated entity properties
                BooleanBuilder filtersByAssociationPredicate = new BooleanBuilder();

                PathBuilder<?> associationPath = associationMap
                        .get(fieldName);
                List<String> associationFields = filterByAssociations
                        .get(fieldName);

                for (String associationFieldName : associationFields) {

                    // On association search, connect
                    // associated entity where clauses by OR
                    // because all assoc entity properties are
                    // inside the same column and any of its
                    // property value can match with given search
                    // value
                    filterExpression = querydslUtilsBean
                            .createFilterExpression(associationPath,
                                    associationFieldName, searchStr);
                    filtersByAssociationPredicate = filtersByAssociationPredicate
                            .or(filterExpression);

                    LOGGER.trace("filtersByAssociationPredicate OR '{}'",
                            filterExpression);
                }

                filtersByColumnPredicate = filtersByColumnPredicate
                        .and(filtersByAssociationPredicate.getValue());

                LOGGER.trace("filtersByColumnPredicate AND '{}'",
                        filtersByAssociationPredicate.getValue());
            }
        }
    }

    LOGGER.debug("Final filtersByColumnPredicate  =  '{}'",
            filtersByColumnPredicate);
    return filtersByColumnPredicate;
}
 
Example #24
Source File: DatatablesUtilsBeanImpl.java    From gvnix with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Prepare search part for a query of findByCriteria
 * 
 * @param entity
 * @param filterByAssociations
 * @param datatablesCriterias
 * @param findInAllColumns
 * @param associationMap
 * @param filtersByTablePredicate
 * @return
 */
private <T> BooleanBuilder prepareQuerySearchPart(PathBuilder<T> entity,
        Map<String, List<String>> filterByAssociations,
        DatatablesCriterias datatablesCriterias, boolean findInAllColumns,
        Map<String, PathBuilder<?>> associationMap,
        BooleanBuilder filtersByTablePredicate) {
    String searchStr = datatablesCriterias.getSearch();
    if (StringUtils.isEmpty(searchStr)) {
        // Nothing to do
        return filtersByTablePredicate;
    }
    LOGGER.debug(
            "Preparing search expression for '{}' string on entity {}...",
            searchStr, entity.getType());
    if (findInAllColumns) {
        boolean expressionExists = false;
        // Add filterable columns only
        for (ColumnDef column : datatablesCriterias.getColumnDefs()) {
            if (column.isFilterable()) {

                // Entity field name and type
                String fieldName = unescapeDot(column.getName());
                LOGGER.trace("Check expression column {}...", fieldName);

                // Find in all columns means we want to find given
                // value in at least one entity property, so we must
                // join the where clauses by OR
                Predicate expression = querydslUtilsBean
                        .createSearchExpression(entity, fieldName,
                                searchStr);
                if (expression != null) {
                    filtersByTablePredicate = filtersByTablePredicate
                            .or(expression);
                    LOGGER.trace("Added expression {}", expression);
                    expressionExists = true;
                }

                // If column is an association and there are given
                // join attributes, add those attributes to WHERE
                // predicates
                List<String> attributes = filterByAssociations
                        .get(fieldName);
                if (attributes != null && attributes.size() > 0) {
                    PathBuilder<?> associationPath = associationMap
                            .get(fieldName);
                    List<String> associationFields = filterByAssociations
                            .get(fieldName);

                    for (String associationFieldName : associationFields) {

                        expression = querydslUtilsBean
                                .createSearchExpression(associationPath,
                                        associationFieldName, searchStr);
                        filtersByTablePredicate = filtersByTablePredicate
                                .or(expression);

                        LOGGER.trace(
                                "Added expression (by association) {}",
                                expression);
                    }
                }
            }
        }
        // If expression is null returns error to returns an empty
        // DataSource
        if (!expressionExists) {
            throw new RuntimeException("Expression cannot be null");
        }
    }
    LOGGER.debug("Search expression: {}", filtersByTablePredicate);
    return filtersByTablePredicate;
}
 
Example #25
Source File: QuerydslUtilsBean.java    From gvnix with GNU General Public License v3.0 4 votes vote down vote up
public <T> Predicate createNumberExpressionGenerics(
PathBuilder<T> entityPath, String fieldName, Class<?> fieldType,
TypeDescriptor descriptor, String searchStr);
 
Example #26
Source File: QuerydslUtilsBean.java    From gvnix with GNU General Public License v3.0 4 votes vote down vote up
public <T> Predicate createNumberExpressionGenericsWithOperators(
PathBuilder<T> entityPath, String fieldName,
TypeDescriptor descriptor, String searchStr);
 
Example #27
Source File: EmployeeService.java    From spring-boot-practice with Apache License 2.0 4 votes vote down vote up
public Page<Employee> findAll(Pageable pageable) {
    Predicate predicate = QEmployee.employee.name.startsWith("e");

    PathBuilder<Employee> builder = new PathBuilder<>(Employee.class, QEmployee.employee.getMetadata());
    Querydsl querydsl = new Querydsl(entityManager, builder);

    JPQLQuery countQuery = createQuery(predicate);
    JPQLQuery query = querydsl.applyPagination(pageable, createQuery(predicate));

    Path<Employee> path = QEmployee.employee;
    Long total = countQuery.count();

    List<Employee> content = total > pageable.getOffset() ? query.list(path) : Collections.<Employee>emptyList();

    return new PageImpl<>(content, pageable, total);
}
 
Example #28
Source File: EntityFunctionPackage.java    From java-platform with Apache License 2.0 4 votes vote down vote up
public boolean exists(Predicate predicate) {
	return baseService.exists(predicate);
}
 
Example #29
Source File: RoleController.java    From java-platform with Apache License 2.0 4 votes vote down vote up
@RequestMapping(value = "/userSelect", method = RequestMethod.GET)
@ResponseBody
public Page<User> userSelect(@RequestParam(value = "id", required = false) Role role, Predicate predicate,
		Pageable pageable) {
	return userService.findAll(QUser.user.userRoles.any().role.eq(role).not().and(predicate), pageable);
}
 
Example #30
Source File: RoleController.java    From java-platform with Apache License 2.0 4 votes vote down vote up
@RequestMapping(value = "/user", method = RequestMethod.GET)
@ResponseBody
public Page<User> user(@RequestParam(value = "id", required = false) Role role, Predicate predicate,
		Pageable pageable) {
	return userService.findAll(QUser.user.userRoles.any().role.eq(role).and(predicate), pageable);
}