Search in sources :

Example 21 with Attribute

use of javax.persistence.metamodel.Attribute in project jbpm by kiegroup.

the class AuditQueryCriteriaUtil method variableInstanceLogSpecificCreatePredicateFromSingleCriteria.

@SuppressWarnings("unchecked")
public static <Q, T> Predicate variableInstanceLogSpecificCreatePredicateFromSingleCriteria(CriteriaQuery<Q> query, CriteriaBuilder builder, QueryCriteria criteria, Root<T> table) {
    Predicate predicate;
    if (LAST_VARIABLE_LIST.equals(criteria.getListId())) {
        Subquery<VariableInstanceLog> maxIdSubQuery = query.subquery(VariableInstanceLog.class);
        Root from = maxIdSubQuery.from(VariableInstanceLog.class);
        maxIdSubQuery.select(builder.max(from.get(VariableInstanceLog_.id)));
        maxIdSubQuery.groupBy(from.get(VariableInstanceLog_.variableId), from.get(VariableInstanceLog_.processInstanceId));
        Attribute varIdField = VariableInstanceLog_.id;
        // TODO: add the current group's criteria list to the subquery,
        // in order to make the subquery more efficient
        // -- but that requires making the criteria list available here as an argument.. :/
        Expression expr;
        if (varIdField instanceof SingularAttribute) {
            expr = table.get((SingularAttribute<T, ?>) varIdField);
        } else {
            throw new IllegalStateException("Unexpected " + varIdField.getClass().getName() + " when processing last variable query criteria!");
        }
        predicate = builder.in(expr).value(maxIdSubQuery);
    } else if (VAR_VALUE_ID_LIST.equals(criteria.getListId())) {
        assert criteria.getValues().size() == 1 : "Only 1 var id/value parameter expected!";
        // extract var/val information from criteria
        Object varVal = criteria.getValues().get(0);
        String[] parts = ((String) varVal).split(VAR_VAL_SEPARATOR, 2);
        String varId = parts[1].substring(0, Integer.parseInt(parts[0]));
        String val = parts[1].substring(Integer.parseInt(parts[0]) + 1);
        // create predicates
        SingularAttribute varVarIdField = VariableInstanceLog_.variableId;
        Path varVarIdPath = table.get(varVarIdField);
        SingularAttribute varValField = VariableInstanceLog_.value;
        Path varValIdPath = table.get(varValField);
        Predicate varIdPredicate = builder.equal(varVarIdPath, varId);
        Predicate valPredicate;
        if (QueryCriteriaType.REGEXP.equals(criteria.getType())) {
            val = convertRegexToJPALikeExpression(val);
            valPredicate = builder.like(varValIdPath, val);
        } else {
            valPredicate = builder.equal(varValIdPath, val);
        }
        // intersect predicates
        predicate = builder.and(varIdPredicate, valPredicate);
    } else {
        throw new IllegalStateException("List id [" + getQueryParameterIdNameMap().get(Integer.parseInt(criteria.getListId())) + "] is not supported for queries on " + table.getJavaType().getSimpleName() + ".");
    }
    return predicate;
}
Also used : Path(javax.persistence.criteria.Path) SingularAttribute(javax.persistence.metamodel.SingularAttribute) Root(javax.persistence.criteria.Root) SingularAttribute(javax.persistence.metamodel.SingularAttribute) Attribute(javax.persistence.metamodel.Attribute) Expression(javax.persistence.criteria.Expression) Predicate(javax.persistence.criteria.Predicate)

Example 22 with Attribute

use of javax.persistence.metamodel.Attribute in project BroadleafCommerce by BroadleafCommerce.

the class FieldPathBuilder method getPath.

@SuppressWarnings({ "rawtypes", "unchecked", "serial" })
public Path getPath(From root, FieldPath fieldPath, final CriteriaBuilder builder) {
    FieldPath myFieldPath = fieldPath;
    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'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;
}
Also used : PluralAttributePath(org.hibernate.ejb.criteria.path.PluralAttributePath) SingularAttributePath(org.hibernate.ejb.criteria.path.SingularAttributePath) Path(javax.persistence.criteria.Path) CriteriaBuilderImpl(org.hibernate.ejb.criteria.CriteriaBuilderImpl) ManagedType(javax.persistence.metamodel.ManagedType) Root(javax.persistence.criteria.Root) Attribute(javax.persistence.metamodel.Attribute) EntityManagerFactoryImpl(org.hibernate.ejb.EntityManagerFactoryImpl) From(javax.persistence.criteria.From) PluralAttributePath(org.hibernate.ejb.criteria.path.PluralAttributePath) SingularAttributePath(org.hibernate.ejb.criteria.path.SingularAttributePath) Metamodel(javax.persistence.metamodel.Metamodel)

Example 23 with Attribute

use of javax.persistence.metamodel.Attribute in project jbpm by kiegroup.

the class QueryCriteriaUtil method getOrderByExpression.

/**
 * @param orderByListId
 * @param queryType
 * @param query
 * @return
 */
protected <T, R> Expression getOrderByExpression(CriteriaQuery<R> query, Class<T> queryType, String orderByListId) {
    Attribute field = getCriteriaAttributes().get(queryType).get(orderByListId);
    assert field != null : "No Attribute found for order-by listId " + orderByListId + " for result type " + queryType.getSimpleName();
    Root table = getRoot(query, queryType);
    assert table != null : "Unable to find proper table (Root) instance in query for result type " + queryType.getSimpleName();
    Path orderByPath;
    if (field instanceof SingularAttribute) {
        orderByPath = table.get((SingularAttribute) field);
    } else {
        throw new UnsupportedOperationException("Ordering by a join field is not supported!");
    }
    return orderByPath;
}
Also used : Path(javax.persistence.criteria.Path) SingularAttribute(javax.persistence.metamodel.SingularAttribute) Root(javax.persistence.criteria.Root) SingularAttribute(javax.persistence.metamodel.SingularAttribute) Attribute(javax.persistence.metamodel.Attribute) PluralAttribute(javax.persistence.metamodel.PluralAttribute)

Example 24 with Attribute

use of javax.persistence.metamodel.Attribute in project jbpm by kiegroup.

the class QueryCriteriaUtil method addCriteria.

public static void addCriteria(Map<Class, Map<String, Attribute>> criteriaAttributes, String listId, Class table, Attribute attr) {
    Map<String, Attribute> tableAttrs = criteriaAttributes.get(table);
    if (tableAttrs == null) {
        tableAttrs = new ConcurrentHashMap<String, Attribute>(1);
        criteriaAttributes.put(table, tableAttrs);
    }
    Attribute previousMapping = tableAttrs.put(listId, attr);
    assert previousMapping == null : "Previous mapping existed for [" + listId + "]!";
}
Also used : SingularAttribute(javax.persistence.metamodel.SingularAttribute) Attribute(javax.persistence.metamodel.Attribute) PluralAttribute(javax.persistence.metamodel.PluralAttribute)

Example 25 with Attribute

use of javax.persistence.metamodel.Attribute in project jbpm by kiegroup.

the class TaskSummaryQueryCriteriaUtil method taskImplSpecificGetEntityField.

@SuppressWarnings("unchecked")
public static <T> Expression taskImplSpecificGetEntityField(CriteriaQuery<T> query, Root<TaskImpl> taskRoot, Join<TaskImpl, TaskDataImpl> taskDataJoin, Join<TaskImpl, PeopleAssignmentsImpl> peopleAssignJoin, String listId, Attribute attr) {
    Expression entityField = null;
    if (attr != null) {
        if (listId.equals(TASK_DESCRIPTION_LIST) || listId.equals(TASK_NAME_LIST) || listId.equals(TASK_SUBJECT_LIST)) {
            // we can *not* query on @LOB annotated fields (and it would be inefficient for a query api to do this?)
            // so we query on the (max 255 char length) string equivalent fields
            entityField = getJoinedEntityField(taskRoot, (Attribute<TaskImpl, I18NTextImpl>) attr, I18NTextImpl_.shortText);
        } else if (listId.equals(ACTUAL_OWNER_ID_LIST) || listId.equals(CREATED_BY_LIST)) {
            if (taskDataJoin == null) {
                taskDataJoin = taskRoot.join(TaskImpl_.taskData);
            }
            // task -> taskData -> (actualOwn/createdBy) UserImpl ->  id
            entityField = getJoinedEntityField(taskDataJoin, (Attribute<TaskDataImpl, UserImpl>) attr, UserImpl_.id);
        } else if (listId.equals(BUSINESS_ADMIN_ID_LIST) || listId.equals(POTENTIAL_OWNER_ID_LIST) || listId.equals(STAKEHOLDER_ID_LIST) || listId.equals(EXCLUDED_OWNER_ID_LIST)) {
            if (peopleAssignJoin == null) {
                peopleAssignJoin = taskRoot.join(TaskImpl_.peopleAssignments);
            }
            // task -> peopleAssignments -> (bus admin/pot owner/stake holder/excl user) OrganizationalEntityImpl ->  id
            entityField = getJoinedEntityField(peopleAssignJoin, (Attribute<PeopleAssignmentsImpl, OrganizationalEntityImpl>) attr, OrganizationalEntityImpl_.id);
        } else {
            if (taskDataJoin == null) {
                taskDataJoin = taskRoot.join(TaskImpl_.taskData);
            }
            Class attrType = attr.getDeclaringType().getJavaType();
            From[] taskRoots = { taskRoot, taskDataJoin };
            for (From from : taskRoots) {
                if (from.getJavaType().equals(attrType)) {
                    if (attr != null) {
                        if (attr instanceof SingularAttribute) {
                            entityField = from.get((SingularAttribute) attr);
                        } else if (attr instanceof PluralAttribute) {
                            entityField = from.get((PluralAttribute) attr);
                        } else {
                            throw new IllegalStateException("Unexpected attribute type when processing criteria with list id " + listId + ": " + attr.getClass().getName());
                        }
                        break;
                    }
                }
            }
        }
    }
    return entityField;
}
Also used : SingularAttribute(javax.persistence.metamodel.SingularAttribute) Expression(javax.persistence.criteria.Expression) SingularAttribute(javax.persistence.metamodel.SingularAttribute) Attribute(javax.persistence.metamodel.Attribute) ListAttribute(javax.persistence.metamodel.ListAttribute) CollectionAttribute(javax.persistence.metamodel.CollectionAttribute) PluralAttribute(javax.persistence.metamodel.PluralAttribute) SetAttribute(javax.persistence.metamodel.SetAttribute) PluralAttribute(javax.persistence.metamodel.PluralAttribute) UserImpl(org.jbpm.services.task.impl.model.UserImpl) From(javax.persistence.criteria.From) TaskDataImpl(org.jbpm.services.task.impl.model.TaskDataImpl)

Aggregations

Attribute (javax.persistence.metamodel.Attribute)31 SingularAttribute (javax.persistence.metamodel.SingularAttribute)21 ListAttribute (javax.persistence.metamodel.ListAttribute)13 PluralAttribute (javax.persistence.metamodel.PluralAttribute)12 MapAttribute (javax.persistence.metamodel.MapAttribute)10 Metamodel (javax.persistence.metamodel.Metamodel)9 CollectionAttribute (javax.persistence.metamodel.CollectionAttribute)6 SetAttribute (javax.persistence.metamodel.SetAttribute)6 Path (javax.persistence.criteria.Path)5 EntityType (javax.persistence.metamodel.EntityType)5 ManagedType (javax.persistence.metamodel.ManagedType)5 EntityManager (javax.persistence.EntityManager)4 TypedQuery (javax.persistence.TypedQuery)4 Predicate (javax.persistence.criteria.Predicate)4 Field (java.lang.reflect.Field)3 Expression (javax.persistence.criteria.Expression)3 From (javax.persistence.criteria.From)3 Root (javax.persistence.criteria.Root)3 IdentifiableType (javax.persistence.metamodel.IdentifiableType)3 Type (javax.persistence.metamodel.Type)3