List of usage examples for javax.persistence.criteria Path getJavaType
Class<? extends X> getJavaType();
From source file:com.mxep.web.common.persistence.DynamicSpecifications.java
private static List<Predicate> getPredicate(Collection<SearchFilter> filters, Root<?> root, CriteriaQuery<?> query, CriteriaBuilder builder) { List<Predicate> predicates = Lists.newArrayList(); for (SearchFilter filter : filters) { // nested path translate, Task??"user.name"filedName, // ?Task.user.name String[] names = StringUtils.split(filter.fieldName, "."); Path expression = root.get(names[0]); for (int i = 1; i < names.length; i++) { expression = expression.get(names[i]); }//from w ww . j av a2 s . co m /*????*/ if (expression.getJavaType().equals(Integer.class) && !filter.operator.equals(SearchFilter.Operator.IN)) { filter.value = Integer.parseInt(filter.value.toString()); } // logic operator switch (filter.operator) { case EQ: predicates.add(builder.equal(expression, filter.value)); break; case LIKE: predicates.add(builder.like(expression, "%" + filter.value + "%")); break; case GT: predicates.add(builder.greaterThan(expression, (Comparable) filter.value)); break; case LT: predicates.add(builder.lessThan(expression, (Comparable) filter.value)); break; case GTE: predicates.add(builder.greaterThanOrEqualTo(expression, (Comparable) filter.value)); break; case LTE: predicates.add(builder.lessThanOrEqualTo(expression, (Comparable) filter.value)); break; case NEQ: predicates.add(builder.notEqual(expression, filter.value)); break; case IN: In in = builder.in(expression); String value = filter.value.toString(); String[] values = StringUtils.split(value, ","); for (int i = 0; i < values.length; i++) { /*????*/ if (expression.getJavaType().equals(Integer.class) || expression.getJavaType().equals(int.class) || expression.getJavaType().equals(byte.class)) { in.value(Integer.valueOf(values[i])); } else { in.value(values[i]); } } predicates.add(in); break; case NULL: predicates.add(builder.isNull(expression)); break; case NOTNULL: predicates.add(builder.isNotNull(expression)); break; } } return predicates; }
From source file:aode.lx.persistence.DynamicSpecifications.java
public static <T> Specification<T> bySearchFilter(final Collection<SearchFilter> filters, final Class<T> entityClazz) { return new Specification<T>() { @Override/*w w w .j a va2 s. c o m*/ public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder builder) { if (Collections3.isNotEmpty(filters)) { List<Predicate> predicates = Lists.newArrayList(); List<Predicate> ORpredicates = Lists.newArrayList(); for (SearchFilter filter : filters) { // nested path translate, Task??"user.name"filedName, ?Task.user.name String[] names = StringUtils.split(filter.fieldName, "."); Path expression = root.get(names[0]); for (int i = 1; i < names.length; i++) { expression = expression.get(names[i]); } Object value = filter.value; if (expression.getJavaType().isEnum()) { value = EnumUtils.valueOf(expression.getJavaType(), filter.value.toString()); predicates.add(builder.equal(expression, value)); } else { // logic operator switch (filter.operator) { case EQ: predicates.add(builder.equal(expression, filter.value)); break; case LIKE: predicates.add(builder.like(expression, "%" + filter.value + "%")); break; case GT: predicates.add(builder.greaterThan(expression, (Comparable) filter.value)); break; case LT: predicates.add(builder.lessThan(expression, (Comparable) filter.value)); break; case GTE: predicates.add(builder.greaterThanOrEqualTo(expression, (Comparable) filter.value)); break; case LTE: predicates.add(builder.lessThanOrEqualTo(expression, (Comparable) filter.value)); break; case NEQ: predicates.add(builder.notEqual(expression, filter.value)); break; case NOTNULL: predicates.add(builder.isNotNull(expression)); break; case ISNULL: predicates.add(builder.isNull(expression)); break; case OREQ: ORpredicates.add(builder.equal(expression, filter.value)); break; case ORLIKE: ORpredicates.add(builder.like(expression, "%" + filter.value + "%")); break; case ORGT: ORpredicates.add(builder.greaterThan(expression, (Comparable) filter.value)); break; case ORLT: ORpredicates.add(builder.lessThan(expression, (Comparable) filter.value)); break; case ORGTE: ORpredicates .add(builder.greaterThanOrEqualTo(expression, (Comparable) filter.value)); break; case ORLTE: ORpredicates.add(builder.lessThanOrEqualTo(expression, (Comparable) filter.value)); break; case ORNEQ: ORpredicates.add(builder.notEqual(expression, filter.value)); break; case ORNOTNULL: ORpredicates.add(builder.isNotNull(expression)); break; case ORISNULL: ORpredicates.add(builder.isNull(expression)); break; } } } // ? and ??? if (!predicates.isEmpty() && !ORpredicates.isEmpty()) { return builder.and(builder.and(predicates.toArray(new Predicate[predicates.size()])), builder.or(ORpredicates.toArray(new Predicate[ORpredicates.size()]))); } if (!predicates.isEmpty()) { return builder.and(predicates.toArray(new Predicate[predicates.size()])); } if (!ORpredicates.isEmpty()) { return builder.or(ORpredicates.toArray(new Predicate[ORpredicates.size()])); } } return builder.conjunction(); } }; }
From source file:org.pushio.webapp.support.persistence.DynamicSpecifications.java
/** * @see ??JPA/*from w w w . ja va2s . c o m*/ * @param filters * @param entityClazz * @param isDistinct trueSQLdistinctfalse? * @return */ public static <T> Specification<T> bySearchFilter(final Collection<SearchFilter> filters, final Class<T> entityClazz, final boolean isDistinct, final List<OrderParam> orderParams) { return new Specification<T>() { @Override public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder builder) { if (orderParams != null && orderParams.size() > 0) { /* CriteriaQuery<Foo> criteriaQuery = criteriaBuilder.createQuery(Foo.class); Root<Foo> from = criteriaQuery.from(Foo.class); CriteriaQuery<Foo> select = criteriaQuery.select(from); criteriaQuery.orderBy(criteriaBuilder.asc(from.get("name"))); */ List<Order> orders = new ArrayList<Order>(orderParams.size()); for (OrderParam orderParam : orderParams) { if (orderParam != null && orderParam.getField() != null) { String fields[] = StringUtil.split(orderParam.getField(), '.'); Path expression = (fields.length > 1) ? root.join(fields[0]) : root.get(fields[0]); for (int i = 1, len = fields.length; i < len; ++i) { expression = expression.get(fields[i]); } if (expression != null) { Order order = (orderParam.getType() == null || orderParam.getType().equalsIgnoreCase("asc")) ? builder.asc(expression) : builder.desc(expression); orders.add(order); // query.orderBy(order); } } } query.orderBy(orders); } query.distinct(isDistinct); if (Collections3.isNotEmpty(filters)) { List<Predicate> predicates = Lists.newArrayList(); for (SearchFilter filter : filters) { // nested path translate, Task??"user.name"filedName, ?Task.user.name String[] names = StringUtils.split(filter.fieldName, '.'); Path expression = null; ////// ? boolean hasJoin = names[0].startsWith("[join]"); String fn = hasJoin ? names[0].substring(6) : names[0]; boolean isNotDateType = !(filter.value instanceof Date); try { expression = hasJoin ? root.join(fn) : root.get(fn); if (isNotDateType && isDateType(expression.getJavaType())) { // filter.value?? filter.value = parseDate(filter.value.toString(), filter.operator); } } catch (Exception e) { // logger.error(e.getMessage(), e); continue; // ?? } boolean isPropertyNotValid = false; for (int i = 1; i < names.length; i++) { try { expression = expression.get(names[i]); if (isNotDateType && isDateType(expression.getJavaType())) { filter.value = parseDate(filter.value.toString(), filter.operator); } } catch (Exception e) { // logger.error(e.getMessage(), e); isPropertyNotValid = true; // break; // ?? } } if (expression == null || isPropertyNotValid) { continue; } /////// // logic operator switch (filter.operator) { case EQ: predicates.add(builder.equal(expression, filter.value)); break; case LIKE: predicates.add(builder.like(expression, "%" + filter.value + "%")); break; case GT: predicates.add(builder.greaterThan(expression, (Comparable) filter.value)); break; case LT: predicates.add(builder.lessThan(expression, (Comparable) filter.value)); break; case GTE: predicates.add(builder.greaterThanOrEqualTo(expression, (Comparable) filter.value)); break; case LTE: predicates.add(builder.lessThanOrEqualTo(expression, (Comparable) filter.value)); break; case ORLIKE: if (filter.value instanceof String) { String value = (String) filter.value; String[] values = value.split(","); Predicate[] like = new Predicate[values.length]; for (int i = 0; i < values.length; i++) { like[i] = builder.like(expression, "%" + values[i] + "%"); } predicates.add(builder.or(like)); } break; case ANDLIKE: if (filter.value instanceof String) { String value = (String) filter.value; String[] values = value.split(","); Predicate[] like = new Predicate[values.length]; for (int i = 0; i < values.length; i++) { like[i] = builder.like(expression, "%" + values[i] + "%"); } predicates.add(builder.and(like)); } break; case ANDNOTLIKE: if (filter.value instanceof String) { String value = (String) filter.value; String[] values = value.split(","); Predicate[] like = new Predicate[values.length]; for (int i = 0; i < values.length; i++) { like[i] = builder.notLike(expression, "%" + values[i] + "%"); } predicates.add(builder.and(like)); } break; case OREQ: if (filter.value instanceof String) { String value = (String) filter.value; String[] values = value.split(","); Predicate[] like = new Predicate[values.length]; for (int i = 0; i < values.length; i++) { like[i] = builder.equal(expression, values[i]); } predicates.add(builder.or(like)); } break; case ANDNOTEQ: if (filter.value instanceof String) { String value = (String) filter.value; String[] values = value.split(","); Predicate[] like = new Predicate[values.length]; for (int i = 0; i < values.length; i++) { like[i] = builder.notEqual(expression, values[i]); } predicates.add(builder.and(like)); } break; case NOTEQ: predicates.add(builder.notEqual(expression, (Comparable) filter.value)); break; case NOTLIKE: predicates.add(builder.notLike(expression, "%" + filter.value + "%")); break; case NULL: predicates.add(builder.isNull(expression)); break; case NOTNULL: predicates.add(builder.isNotNull(expression)); break; // case IN: // predicates.add(builder.in(expression).in(values)); // break; } } // ? and ??? if (!predicates.isEmpty()) { return builder.and(predicates.toArray(new Predicate[predicates.size()])); } } return builder.conjunction(); } }; }
From source file:org.broadleafcommerce.openadmin.server.service.persistence.module.AdornedTargetListPersistenceModule.java
public List<FilterMapping> getAdornedTargetFilterMappings(PersistencePerspective persistencePerspective, CriteriaTransferObject cto, Map<String, FieldMetadata> mergedProperties, AdornedTargetList adornedTargetList) throws ClassNotFoundException { List<FilterMapping> filterMappings = getFilterMappings(persistencePerspective, cto, adornedTargetList.getAdornedTargetEntityClassname(), mergedProperties); FilterMapping filterMapping = new FilterMapping() .withFieldPath(new FieldPath().withTargetProperty( adornedTargetList.getLinkedObjectPath() + "." + adornedTargetList.getLinkedIdProperty())) .withFilterValues(cto.get(adornedTargetList.getCollectionFieldName()).getFilterValues()) .withRestriction(/*from w ww.ja va2 s .co m*/ new Restriction().withPredicateProvider(new PredicateProvider<Serializable, String>() { @Override public Predicate buildPredicate(CriteriaBuilder builder, FieldPathBuilder fieldPathBuilder, From root, String ceilingEntity, String fullPropertyName, Path<Serializable> explicitPath, List<String> directValues) { if (String.class.isAssignableFrom(explicitPath.getJavaType())) { return builder.equal(explicitPath, directValues.get(0)); } else { return builder.equal(explicitPath, Long.parseLong(directValues.get(0))); } } })); filterMappings.add(filterMapping); FilterMapping filterMapping2 = new FilterMapping() .withFieldPath(new FieldPath().withTargetProperty( adornedTargetList.getTargetObjectPath() + "." + adornedTargetList.getTargetIdProperty())) .withFilterValues(cto.get(adornedTargetList.getCollectionFieldName() + "Target").getFilterValues()) .withRestriction( new Restriction().withPredicateProvider(new PredicateProvider<Serializable, String>() { @Override public Predicate buildPredicate(CriteriaBuilder builder, FieldPathBuilder fieldPathBuilder, From root, String ceilingEntity, String fullPropertyName, Path<Serializable> explicitPath, List<String> directValues) { if (String.class.isAssignableFrom(explicitPath.getJavaType())) { return builder.equal(explicitPath, directValues.get(0)); } else { return builder.equal(explicitPath, Long.parseLong(directValues.get(0))); } } })); filterMappings.add(filterMapping2); return filterMappings; }
From source file:org.broadleafcommerce.openadmin.server.service.persistence.module.criteria.CriteriaTranslatorImpl.java
protected void addSorting(CriteriaBuilder criteriaBuilder, List<Order> sorts, FilterMapping filterMapping, Path path) { Expression exp = path;//from w ww . ja va2 s .c om if (filterMapping.getNullsLast() != null && filterMapping.getNullsLast()) { Object largeValue = getAppropriateLargeSortingValue(path.getJavaType()); if (largeValue != null) { exp = criteriaBuilder.coalesce(path, largeValue); } } if (SortDirection.ASCENDING == filterMapping.getSortDirection()) { sorts.add(criteriaBuilder.asc(exp)); } else { sorts.add(criteriaBuilder.desc(exp)); } }
From source file:org.broadleafcommerce.openadmin.server.service.persistence.module.criteria.FieldPathBuilder.java
@SuppressWarnings({ "rawtypes", "unchecked", "serial" }) public Path getPath(From root, FieldPath fieldPath, final CriteriaBuilder builder) { FieldPath myFieldPath = fieldPath;//from w w w.ja v a 2 s.c o m if (!StringUtils.isEmpty(fieldPath.getTargetProperty())) { myFieldPath = getFieldPath(root, fieldPath.getTargetProperty()); } From myRoot = root; for (String pathElement : myFieldPath.getAssociationPath()) { myRoot = myRoot.join(pathElement); } Path path = myRoot; for (int i = 0; i < myFieldPath.getTargetPropertyPieces().size(); i++) { String piece = myFieldPath.getTargetPropertyPieces().get(i); if (path.getJavaType().isAnnotationPresent(Embeddable.class)) { String original = ((SingularAttributePath) path).getAttribute().getDeclaringType().getJavaType() .getName() + "." + ((SingularAttributePath) path).getAttribute().getName() + "." + piece; String copy = path.getJavaType().getName() + "." + piece; copyCollectionPersister(original, copy, ((CriteriaBuilderImpl) builder).getEntityManagerFactory().getSessionFactory()); } try { path = path.get(piece); } catch (IllegalArgumentException e) { // We weren't able to resolve the requested piece, likely because it's in a polymoprhic version // of the path we're currently on. Let's see if there's any polymoprhic version of our class to // use instead. EntityManagerFactoryImpl em = ((CriteriaBuilderImpl) builder).getEntityManagerFactory(); Metamodel mm = em.getMetamodel(); boolean found = false; Class<?>[] polyClasses = dynamicDaoHelper.getAllPolymorphicEntitiesFromCeiling(path.getJavaType(), em.getSessionFactory(), true, true); for (Class<?> clazz : polyClasses) { ManagedType mt = mm.managedType(clazz); try { Attribute attr = mt.getAttribute(piece); if (attr != null) { Root additionalRoot = criteria.from(clazz); restrictions.add(builder.equal(path, additionalRoot)); path = additionalRoot.get(piece); found = true; break; } } catch (IllegalArgumentException e2) { // Do nothing - we'll try the next class and see if it has the attribute } } if (!found) { throw new IllegalArgumentException( "Could not resolve requested attribute against path, including" + " known polymorphic versions of the root", e); } } if (path.getParentPath() != null && path.getParentPath().getJavaType().isAnnotationPresent(Embeddable.class) && path instanceof PluralAttributePath) { //We need a workaround for this problem until it is resolved in Hibernate (loosely related to and likely resolved by https://hibernate.atlassian.net/browse/HHH-8802) //We'll throw a specialized exception (and handle in an alternate flow for calls from BasicPersistenceModule) throw new CriteriaConversionException(String.format( "Unable to create a JPA criteria Path through an @Embeddable object to a collection that resides therein (%s)", fieldPath.getTargetProperty()), fieldPath); // //TODO this code should work, but there still appear to be bugs in Hibernate's JPA criteria handling for lists // //inside Embeddables // Class<?> myClass = ((PluralAttributePath) path).getAttribute().getClass().getInterfaces()[0]; // //we don't know which version of "join" to call, so we'll let reflection figure it out // try { // From embeddedJoin = myRoot.join(((SingularAttributePath) path.getParentPath()).getAttribute()); // Method join = embeddedJoin.getClass().getMethod("join", myClass); // path = (Path) join.invoke(embeddedJoin, ((PluralAttributePath) path).getAttribute()); // } catch (Exception e) { // throw new RuntimeException(e); // } } } return path; }