Example usage for javax.persistence.criteria CriteriaBuilder equal

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

Introduction

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

Prototype

Predicate equal(Expression<?> x, Object y);

Source Link

Document

Create a predicate for testing the arguments for equality.

Usage

From source file:net.sf.gazpachoquest.qbe.ByExampleSpecification.java

public <T extends Persistable> Specification<T> byExampleOnEntity(final T example, final SearchParameters sp) {
    Validate.notNull(example, "example must not be null");

    return new Specification<T>() {

        @Override/*w ww . j  a va  2s.  co  m*/
        public Predicate toPredicate(final Root<T> rootPath, final CriteriaQuery<?> query,
                final CriteriaBuilder builder) {
            Class<T> type = rootPath.getModel().getBindableJavaType();

            ManagedType<T> mt = em.getMetamodel().entity(type);

            List<Predicate> predicates = new ArrayList<Predicate>();
            predicates.addAll(byExample(mt, rootPath, example, sp, builder));
            predicates.addAll(byExampleOnXToOne(mt, rootPath, example, sp, builder));
            // 1 level deep only
            predicates.addAll(byExampleOnManyToMany(mt, rootPath, example, sp, builder));
            // order by
            query.orderBy(JpaUtil.buildJpaOrders(sp.getOrders(), rootPath, builder));
            return JpaUtil.andPredicate(builder, predicates);
        }

        //https://github.com/jaxio/generated-projects/tree/master/jsf2-spring-conversation/src/main/generated-java/com/jaxio/appli/repository/support

        public <T extends Persistable> List<Predicate> byExample(final ManagedType<T> mt, final Path<T> mtPath,
                final T mtValue, final SearchParameters sp, final CriteriaBuilder builder) {
            List<Predicate> predicates = new ArrayList<Predicate>();
            for (SingularAttribute<? super T, ?> attr : mt.getSingularAttributes()) {
                if (attr.getPersistentAttributeType() == MANY_TO_ONE
                        || attr.getPersistentAttributeType() == ONE_TO_ONE
                        || attr.getPersistentAttributeType() == EMBEDDED
                        || attr.getJavaType().isAssignableFrom(Map.class)) {
                    continue;
                }
                Object attrValue = getValue(mtValue, attr);

                if (attrValue != null) {
                    if (attr.getJavaType() == String.class) {
                        if (isNotEmpty((String) attrValue)) {
                            SingularAttribute<? super T, String> stringAttribute = mt
                                    .getSingularAttribute(attr.getName(), String.class);
                            predicates.add(JpaUtil.stringPredicate(mtPath.get(stringAttribute), attrValue, sp,
                                    builder));
                        }
                    } else {
                        SingularAttribute<? super T, ?> attribute = mt.getSingularAttribute(attr.getName(),
                                attr.getJavaType());
                        // apply equal
                        predicates.add(builder.equal(mtPath.get(attribute), attrValue));
                    }
                }
            }
            return predicates;
        }

        /**
         * Construct a join predicate on collection (eg many to many, List)
         */
        public <T extends Persistable> List<Predicate> byExampleOnManyToMany(final ManagedType<T> mt,
                final Root<T> mtPath, final T mtValue, final SearchParameters sp,
                final CriteriaBuilder builder) {
            List<Predicate> predicates = new ArrayList<Predicate>();
            for (PluralAttribute<T, ?, ?> pa : mt.getDeclaredPluralAttributes()) {
                if (pa.getCollectionType() == PluralAttribute.CollectionType.LIST) {
                    List<?> value = (List<?>) getValue(mtValue, mt.getAttribute(pa.getName()));

                    if (value != null && !value.isEmpty()) {
                        ListJoin<T, ?> join = mtPath.join(mt.getDeclaredList(pa.getName()));
                        predicates.add(join.in(value));
                    }
                }
                if (pa.getCollectionType() == PluralAttribute.CollectionType.SET) {
                    Set<?> value = (Set<?>) getValue(mtValue, mt.getAttribute(pa.getName()));

                    if (value != null && !value.isEmpty()) {
                        SetJoin<T, ?> join = mtPath.join(mt.getDeclaredSet(pa.getName()));
                        predicates.add(join.in(value));
                    }
                }
            }
            return predicates;
        }

        /**
         * 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.
         */
        @SuppressWarnings("unchecked")
        public <T extends Persistable, M2O extends Persistable> List<Predicate> byExampleOnXToOne(
                final ManagedType<T> mt, final Root<T> mtPath, final T mtValue, final SearchParameters sp,
                final CriteriaBuilder builder) {
            List<Predicate> predicates = new ArrayList<Predicate>();
            for (SingularAttribute<? super T, ?> attr : mt.getSingularAttributes()) {
                if (attr.getPersistentAttributeType() == MANY_TO_ONE
                        || attr.getPersistentAttributeType() == ONE_TO_ONE) { //
                    M2O m2oValue = (M2O) getValue(mtValue, mt.getAttribute(attr.getName()));

                    if (m2oValue != null) {
                        Class<M2O> m2oType = (Class<M2O>) attr.getBindableJavaType();
                        ManagedType<M2O> m2oMt = em.getMetamodel().entity(m2oType);
                        Path<M2O> m2oPath = (Path<M2O>) mtPath.get(attr);
                        predicates.addAll(byExample(m2oMt, m2oPath, m2oValue, sp, builder));
                    }
                }
            }
            return predicates;
        }

        private <T> Object getValue(final T example, final Attribute<? super T, ?> attr) {
            Object value = null;
            try {
                if (attr.getJavaMember() instanceof Method) {
                    value = ((Method) attr.getJavaMember()).invoke(example, new Object[0]);
                } else if (attr.getJavaMember() instanceof Field) {
                    value = ReflectionUtils.getField((Field) attr.getJavaMember(), example);
                }

                if (value instanceof ValueHolderInterface) {
                    value = ((ValueHolderInterface) value).getValue();
                }

            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            } catch (InvocationTargetException e) {
                throw new RuntimeException(e);
            }
            return value;
        }

    };

}

From source file:ca.uhn.fhir.jpa.dao.SearchBuilder.java

private void createPredicateResourceId(CriteriaBuilder builder, CriteriaQuery<?> cq,
        List<Predicate> thePredicates, Expression<Long> theExpression) {
    if (myParams.isPersistResults()) {
        if (mySearchEntity.getTotalCount() > -1) {
            Subquery<Long> subQ = cq.subquery(Long.class);
            Root<SearchResult> subQfrom = subQ.from(SearchResult.class);
            subQ.select(subQfrom.get("myResourcePid").as(Long.class));
            Predicate subQname = builder.equal(subQfrom.get("mySearch"), mySearchEntity);
            subQ.where(subQname);/*w  w w.  j  a  v  a  2s .  c om*/

            thePredicates.add(theExpression.in(subQ));
        }
    } else {
        if (myPids != null) {
            thePredicates.add(theExpression.in(myPids));
        }
    }

}

From source file:ca.uhn.fhir.jpa.dao.SearchBuilder.java

private void addPredicateParamMissing(String joinName, String theParamName,
        Class<? extends BaseResourceIndexedSearchParam> theParamTable) {
    CriteriaBuilder builder = myEntityManager.getCriteriaBuilder();
    CriteriaQuery<Long> cq = builder.createQuery(Long.class);
    Root<ResourceTable> from = cq.from(ResourceTable.class);
    cq.select(from.get("myId").as(Long.class));

    Subquery<Long> subQ = cq.subquery(Long.class);
    Root<? extends BaseResourceIndexedSearchParam> subQfrom = subQ.from(theParamTable);
    subQ.select(subQfrom.get("myResourcePid").as(Long.class));
    Predicate subQname = builder.equal(subQfrom.get("myParamName"), theParamName);
    Predicate subQtype = builder.equal(subQfrom.get("myResourceType"), myResourceName);
    subQ.where(builder.and(subQtype, subQname));

    List<Predicate> predicates = new ArrayList<Predicate>();
    predicates.add(builder.not(builder.in(from.get("myId")).value(subQ)));
    predicates.add(builder.equal(from.get("myResourceType"), myResourceName));
    predicates.add(builder.isNull(from.get("myDeleted")));
    createPredicateResourceId(builder, cq, predicates, from.get("myId").as(Long.class));

    cq.where(builder.and(toArray(predicates)));

    ourLog.info("Adding :missing qualifier for parameter '{}'", theParamName);

    TypedQuery<Long> q = myEntityManager.createQuery(cq);
    doSetPids(q.getResultList());//from w ww. j  a v a2s. c  om
}

From source file:com.sammyun.dao.impl.BaseDaoImpl.java

private void addRestrictions(CriteriaQuery<T> criteriaQuery, List<Filter> filters) {
    if (criteriaQuery == null || filters == null || filters.isEmpty()) {
        return;//from w  w  w . j  a v a2 s.  c  om
    }
    Root<T> root = getRoot(criteriaQuery);
    if (root == null) {
        return;
    }
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();

    Predicate restrictions = criteriaQuery.getRestriction() != null ? criteriaQuery.getRestriction()
            : criteriaBuilder.conjunction();
    for (Filter filter : filters) {
        if (filter == null || StringUtils.isEmpty(filter.getProperty())) {
            continue;
        }

        /**  */
        if (filter.getMold() == Mold.dl || filter.getMold() == Mold.dg) {
            if (filter.getOperator() == Operator.lt && filter.getValue() != null) {
                restrictions = criteriaBuilder.and(restrictions,
                        criteriaBuilder.lessThan(root.<Date>get(filter.getProperty()),
                                DateUtil.parseDate(filter.getValue().toString())));
            } else if (filter.getOperator() == Operator.gt && filter.getValue() != null) {
                restrictions = criteriaBuilder.and(restrictions,
                        criteriaBuilder.greaterThan(root.<Date>get(filter.getProperty()),
                                DateUtil.parseDate(filter.getValue().toString())));
            } else if (filter.getOperator() == Operator.le && filter.getValue() != null) {
                restrictions = criteriaBuilder.and(restrictions,
                        criteriaBuilder.lessThanOrEqualTo(root.<Date>get(filter.getProperty()),
                                DateUtil.parseDate(filter.getValue().toString())));
            } else if (filter.getOperator() == Operator.ge && filter.getValue() != null) {
                restrictions = criteriaBuilder.and(restrictions,
                        criteriaBuilder.greaterThanOrEqualTo(root.<Date>get(filter.getProperty()),
                                DateUtil.parseDate(filter.getValue().toString())));
            }

        } else {

            if (filter.getOperator() == Operator.eq && filter.getValue() != null) {
                if (filter.getIgnoreCase() != null && filter.getIgnoreCase()
                        && filter.getValue() instanceof String) {
                    restrictions = criteriaBuilder.and(restrictions,
                            criteriaBuilder.equal(criteriaBuilder.lower(root.<String>get(filter.getProperty())),
                                    ((String) filter.getValue()).toLowerCase()));
                } else {
                    restrictions = criteriaBuilder.and(restrictions,
                            criteriaBuilder.equal(root.get(filter.getProperty()), filter.getValue()));
                }
            } else if (filter.getOperator() == Operator.ne && filter.getValue() != null) {
                if (filter.getIgnoreCase() != null && filter.getIgnoreCase()
                        && filter.getValue() instanceof String) {
                    restrictions = criteriaBuilder.and(restrictions,
                            criteriaBuilder.notEqual(
                                    criteriaBuilder.lower(root.<String>get(filter.getProperty())),
                                    ((String) filter.getValue()).toLowerCase()));
                } else {
                    restrictions = criteriaBuilder.and(restrictions,
                            criteriaBuilder.notEqual(root.get(filter.getProperty()), filter.getValue()));
                }
            } else if (filter.getOperator() == Operator.gt && filter.getValue() != null) {
                restrictions = criteriaBuilder.and(restrictions,
                        criteriaBuilder.gt(root.<Number>get(filter.getProperty()), (Number) filter.getValue()));

            } else if (filter.getOperator() == Operator.lt && filter.getValue() != null) {
                restrictions = criteriaBuilder.and(restrictions,
                        criteriaBuilder.lt(root.<Number>get(filter.getProperty()), (Number) filter.getValue()));
            } else if (filter.getOperator() == Operator.ge && filter.getValue() != null) {
                restrictions = criteriaBuilder.and(restrictions,
                        criteriaBuilder.ge(root.<Number>get(filter.getProperty()), (Number) filter.getValue()));
            } else if (filter.getOperator() == Operator.le && filter.getValue() != null) {
                restrictions = criteriaBuilder.and(restrictions,
                        criteriaBuilder.le(root.<Number>get(filter.getProperty()), (Number) filter.getValue()));
            } else if (filter.getOperator() == Operator.like && filter.getValue() != null
                    && filter.getValue() instanceof String) {
                restrictions = criteriaBuilder.and(restrictions, criteriaBuilder
                        .like(root.<String>get(filter.getProperty()), (String) filter.getValue()));
            } else if (filter.getOperator() == Operator.in && filter.getValue() != null) {
                restrictions = criteriaBuilder.and(restrictions,
                        root.get(filter.getProperty()).in(filter.getValue()));
            } else if (filter.getOperator() == Operator.isNull) {
                restrictions = criteriaBuilder.and(restrictions, root.get(filter.getProperty()).isNull());
            } else if (filter.getOperator() == Operator.isNotNull) {
                restrictions = criteriaBuilder.and(restrictions, root.get(filter.getProperty()).isNotNull());
            }
        }
    }
    criteriaQuery.where(restrictions);
}

From source file:ch.puzzle.itc.mobiliar.business.server.boundary.ServerView.java

public List<ServerTuple> getAppServers(String hostFilter, String appServerFilter, String runtimeFilter,
        String nodeFilter, String contextFilter) {

    CriteriaBuilder cb = entityManager.getCriteriaBuilder();

    CriteriaQuery<ServerTuple> q = cb.createQuery(ServerTuple.class);

    //get Node ResType
    Root<ResourceEntity> node = q.from(ResourceEntity.class);
    Join<ResourceEntity, ResourceTypeEntity> nodeType = node.join("resourceType", JoinType.LEFT);
    Join<ResourceEntity, ReleaseEntity> nodeRelease = node.join("release", JoinType.LEFT);

    //get AppServer
    Join<ResourceEntity, ConsumedResourceRelationEntity> nodeResRel = node.join("consumedSlaveRelations",
            JoinType.LEFT);/*from w w w  .j ava 2  s  . c  o m*/
    Join<ConsumedResourceRelationEntity, ResourceEntity> appServer = nodeResRel.join("masterResource",
            JoinType.LEFT);
    Join<ResourceEntity, ReleaseEntity> asRelease = appServer.join("release", JoinType.LEFT);
    Join<ResourceEntity, ResourceTypeEntity> asType = appServer.join("resourceType", JoinType.LEFT);

    //get Runtime of as
    Join<ResourceEntity, ConsumedResourceRelationEntity> asResRel = appServer.join("consumedMasterRelations",
            JoinType.LEFT);
    Join<ConsumedResourceRelationEntity, ResourceEntity> asRuntime = asResRel.join("slaveResource",
            JoinType.LEFT);
    Join<ResourceEntity, ResourceTypeEntity> runtimeType = asRuntime.join("resourceType", JoinType.LEFT);

    //get Props between as and node
    Join<ConsumedResourceRelationEntity, ResourceRelationContextEntity> resRelCtx = nodeResRel.join("contexts",
            JoinType.LEFT);
    Join<ResourceRelationContextEntity, ContextEntity> asCtx = resRelCtx.join("context", JoinType.LEFT);
    Join<ContextEntity, ContextEntity> asDomain = asCtx.join("parent", JoinType.LEFT);

    Join<ResourceRelationContextEntity, PropertyEntity> asProp = resRelCtx.join("properties", JoinType.LEFT);
    //here an on clause should be added, so we don't get hostnames that are divined directly on the node multiple times (and descriptor.propertyName = 'hostName')
    //on support was added in jpa 2.1 which is part of JEE 7
    Join<PropertyEntity, PropertyDescriptorEntity> asPropType = asProp.join("descriptor", JoinType.LEFT);

    q.select(cb.construct(ServerTuple.class, asProp.get("value"), appServer.get("name"), appServer.get("id"),
            asRelease.get("name"), asRuntime.get("name"), node.get("name"), node.get("id"),
            nodeRelease.get("name"), asDomain.get("name"), asDomain.get("id"), asCtx.get("name"),
            asCtx.get("id"), cb.literal(0) //false
    ));

    Predicate p = cb.and(cb.equal(nodeType.get("name"), DefaultResourceTypeDefinition.NODE.name()),
            cb.equal(asType.get("name"), DefaultResourceTypeDefinition.APPLICATIONSERVER.name()),
            cb.or(cb.equal(runtimeType.get("name"), ResourceTypeEntity.RUNTIME),
                    cb.isNull(runtimeType.get("name"))),
            cb.isNotNull(asProp.get("value")), cb.equal(asPropType.get("propertyName"), "hostName"));

    p = addFilters(p, cb, hostFilter, appServerFilter, runtimeFilter, nodeFilter, contextFilter,
            asProp.<String>get("value"), appServer.<String>get("name"), asRuntime.<String>get("name"),
            node.<String>get("name"), asCtx.<String>get("name"));

    q.where(p);

    TypedQuery<ServerTuple> query = entityManager.createQuery(q);
    List<ServerTuple> servers = query.getResultList();

    return servers;
}

From source file:ca.uhn.fhir.jpa.dao.BaseFhirResourceDao.java

private Set<Long> addPredicateToken(String theParamName, Set<Long> thePids,
        List<? extends IQueryParameterType> theList) {
    if (theList == null || theList.isEmpty()) {
        return thePids;
    }//from  w  w  w. j a  v a 2  s. c om

    CriteriaBuilder builder = myEntityManager.getCriteriaBuilder();
    CriteriaQuery<Long> cq = builder.createQuery(Long.class);
    Root<ResourceIndexedSearchParamToken> from = cq.from(ResourceIndexedSearchParamToken.class);
    cq.select(from.get("myResourcePid").as(Long.class));

    List<Predicate> codePredicates = new ArrayList<Predicate>();
    for (IQueryParameterType nextOr : theList) {
        if (nextOr instanceof TokenParam) {
            TokenParam id = (TokenParam) nextOr;
            if (id.isText()) {
                return addPredicateString(theParamName, thePids, theList);
            }
        }

        Predicate singleCode = createPredicateToken(nextOr, theParamName, builder, from);
        codePredicates.add(singleCode);
    }

    Predicate masterCodePredicate = builder.or(codePredicates.toArray(new Predicate[0]));

    Predicate type = builder.equal(from.get("myResourceType"), myResourceName);
    Predicate name = builder.equal(from.get("myParamName"), theParamName);
    if (thePids.size() > 0) {
        Predicate inPids = (from.get("myResourcePid").in(thePids));
        cq.where(builder.and(type, name, masterCodePredicate, inPids));
    } else {
        cq.where(builder.and(type, name, masterCodePredicate));
    }

    TypedQuery<Long> q = myEntityManager.createQuery(cq);
    return new HashSet<Long>(q.getResultList());
}

From source file:ca.uhn.fhir.jpa.dao.BaseFhirResourceDao.java

private Set<Long> addPredicateLanguage(Set<Long> thePids, List<List<? extends IQueryParameterType>> theList) {
    if (theList == null || theList.isEmpty()) {
        return thePids;
    }//from   w  w  w . j a  v a2s .c o m
    if (theList.size() > 1) {
        throw new InvalidRequestException(
                "Language parameter can not have more than one AND value, found " + theList.size());
    }

    CriteriaBuilder builder = myEntityManager.getCriteriaBuilder();
    CriteriaQuery<Long> cq = builder.createQuery(Long.class);
    Root<ResourceTable> from = cq.from(ResourceTable.class);
    cq.select(from.get("myId").as(Long.class));

    Set<String> values = new HashSet<String>();
    for (IQueryParameterType next : theList.get(0)) {
        if (next instanceof StringParam) {
            String nextValue = ((StringParam) next).getValue();
            if (isBlank(nextValue)) {
                continue;
            }
            values.add(nextValue);
        } else {
            throw new InternalErrorException("Lanugage parameter must be of type "
                    + StringParam.class.getCanonicalName() + " - Got " + next.getClass().getCanonicalName());
        }
    }

    if (values.isEmpty()) {
        return thePids;
    }

    Predicate typePredicate = builder.equal(from.get("myResourceType"), myResourceName);
    Predicate langPredicate = from.get("myLanguage").as(String.class).in(values);
    Predicate masterCodePredicate = builder.and(typePredicate, langPredicate);

    if (thePids.size() > 0) {
        Predicate inPids = (from.get("myId").in(thePids));
        cq.where(builder.and(masterCodePredicate, inPids));
    } else {
        cq.where(masterCodePredicate);
    }

    TypedQuery<Long> q = myEntityManager.createQuery(cq);
    return new HashSet<Long>(q.getResultList());
}

From source file:ca.uhn.fhir.jpa.dao.SearchBuilder.java

private boolean addPredicateMissingFalseIfPresent(CriteriaBuilder theBuilder, String theParamName,
        Root<? extends BaseResourceIndexedSearchParam> from, List<Predicate> codePredicates,
        IQueryParameterType nextOr) {/*from  w  ww. j  a va 2 s.  c o m*/
    boolean missingFalse = false;
    if (nextOr.getMissing() != null) {
        if (nextOr.getMissing().booleanValue() == true) {
            throw new InvalidRequestException(myContext.getLocalizer().getMessage(BaseHapiFhirResourceDao.class,
                    "multipleParamsWithSameNameOneIsMissingTrue", theParamName));
        }
        Predicate singleCode = from.get("myId").isNotNull();
        Predicate name = theBuilder.equal(from.get("myParamName"), theParamName);
        codePredicates.add(theBuilder.and(name, singleCode));
        missingFalse = true;
    }
    return missingFalse;
}

From source file:ca.uhn.fhir.jpa.dao.BaseFhirResourceDao.java

private Set<Long> addPredicateComposite(RuntimeSearchParam theParamDef, Set<Long> thePids,
        List<? extends IQueryParameterType> theNextAnd) {
    CriteriaBuilder builder = myEntityManager.getCriteriaBuilder();
    CriteriaQuery<Long> cq = builder.createQuery(Long.class);
    Root<ResourceTable> from = cq.from(ResourceTable.class);
    cq.select(from.get("myId").as(Long.class));

    IQueryParameterType or = theNextAnd.get(0);
    if (!(or instanceof CompositeParam<?, ?>)) {
        throw new InvalidRequestException("Invalid type for composite param (must be "
                + CompositeParam.class.getSimpleName() + ": " + or.getClass());
    }/*from   ww  w  .j  av  a  2s  .  c  om*/
    CompositeParam<?, ?> cp = (CompositeParam<?, ?>) or;

    RuntimeSearchParam left = theParamDef.getCompositeOf().get(0);
    IQueryParameterType leftValue = cp.getLeftValue();
    Predicate leftPredicate = createCompositeParamPart(builder, from, left, leftValue);

    RuntimeSearchParam right = theParamDef.getCompositeOf().get(1);
    IQueryParameterType rightValue = cp.getRightValue();
    Predicate rightPredicate = createCompositeParamPart(builder, from, right, rightValue);

    Predicate type = builder.equal(from.get("myResourceType"), myResourceName);
    if (thePids.size() > 0) {
        Predicate inPids = (from.get("myResourcePid").in(thePids));
        cq.where(builder.and(type, leftPredicate, rightPredicate, inPids));
    } else {
        cq.where(builder.and(type, leftPredicate, rightPredicate));
    }

    TypedQuery<Long> q = myEntityManager.createQuery(cq);
    return new HashSet<Long>(q.getResultList());

}