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:io.apiman.manager.api.jpa.JpaStorage.java

/**
 * @see io.apiman.manager.api.core.IStorageQuery#getUserMemberships(java.lang.String)
 *//*from   ww w .j  a v a 2s.  co  m*/
@Override
public Set<RoleMembershipBean> getUserMemberships(String userId) throws StorageException {
    Set<RoleMembershipBean> memberships = new HashSet<>();
    beginTx();
    try {
        EntityManager entityManager = getActiveEntityManager();
        CriteriaBuilder builder = entityManager.getCriteriaBuilder();
        CriteriaQuery<RoleMembershipBean> criteriaQuery = builder.createQuery(RoleMembershipBean.class);
        Root<RoleMembershipBean> from = criteriaQuery.from(RoleMembershipBean.class);
        criteriaQuery.where(builder.equal(from.get("userId"), userId));
        TypedQuery<RoleMembershipBean> typedQuery = entityManager.createQuery(criteriaQuery);
        List<RoleMembershipBean> resultList = typedQuery.getResultList();
        memberships.addAll(resultList);
        return memberships;
    } catch (Throwable t) {
        logger.error(t.getMessage(), t);
        throw new StorageException(t);
    } finally {
        rollbackTx();
    }
}

From source file:io.apiman.manager.api.jpa.JpaStorage.java

/**
 * @see io.apiman.manager.api.core.IStorageQuery#getOrgMemberships(java.lang.String)
 *//*from  w  w  w  .  ja  va2 s .  co  m*/
@Override
public Set<RoleMembershipBean> getOrgMemberships(String organizationId) throws StorageException {
    Set<RoleMembershipBean> memberships = new HashSet<>();
    beginTx();
    try {
        EntityManager entityManager = getActiveEntityManager();
        CriteriaBuilder builder = entityManager.getCriteriaBuilder();
        CriteriaQuery<RoleMembershipBean> criteriaQuery = builder.createQuery(RoleMembershipBean.class);
        Root<RoleMembershipBean> from = criteriaQuery.from(RoleMembershipBean.class);
        criteriaQuery.where(builder.equal(from.get("organizationId"), organizationId));
        TypedQuery<RoleMembershipBean> typedQuery = entityManager.createQuery(criteriaQuery);
        List<RoleMembershipBean> resultList = typedQuery.getResultList();
        memberships.addAll(resultList);
        return memberships;
    } catch (Throwable t) {
        logger.error(t.getMessage(), t);
        throw new StorageException(t);
    } finally {
        rollbackTx();
    }
}

From source file:io.apiman.manager.api.jpa.JpaStorage.java

/**
 * @see io.apiman.manager.api.core.IStorageQuery#getUserMemberships(java.lang.String, java.lang.String)
 *///from   w  w  w.  j a  va  2s  .  c o m
@Override
public Set<RoleMembershipBean> getUserMemberships(String userId, String organizationId)
        throws StorageException {
    Set<RoleMembershipBean> memberships = new HashSet<>();
    beginTx();
    try {
        EntityManager entityManager = getActiveEntityManager();
        CriteriaBuilder builder = entityManager.getCriteriaBuilder();
        CriteriaQuery<RoleMembershipBean> criteriaQuery = builder.createQuery(RoleMembershipBean.class);
        Root<RoleMembershipBean> from = criteriaQuery.from(RoleMembershipBean.class);
        criteriaQuery.where(builder.equal(from.get("userId"), userId),
                builder.equal(from.get("organizationId"), organizationId));
        TypedQuery<RoleMembershipBean> typedQuery = entityManager.createQuery(criteriaQuery);
        List<RoleMembershipBean> resultList = typedQuery.getResultList();
        memberships.addAll(resultList);
        return memberships;
    } catch (Throwable t) {
        logger.error(t.getMessage(), t);
        throw new StorageException(t);
    } finally {
        rollbackTx();
    }
}

From source file:io.apiman.manager.api.jpa.JpaStorage.java

/**
 * @see io.apiman.manager.api.core.IStorageQuery#getPermissions(java.lang.String)
 *//*  w w  w.j av a2s .c o  m*/
@Override
public Set<PermissionBean> getPermissions(String userId) throws StorageException {
    Set<PermissionBean> permissions = new HashSet<>();
    beginTx();
    try {
        EntityManager entityManager = getActiveEntityManager();
        CriteriaBuilder builder = entityManager.getCriteriaBuilder();
        CriteriaQuery<RoleMembershipBean> criteriaQuery = builder.createQuery(RoleMembershipBean.class);
        Root<RoleMembershipBean> from = criteriaQuery.from(RoleMembershipBean.class);
        criteriaQuery.where(builder.equal(from.get("userId"), userId));
        TypedQuery<RoleMembershipBean> typedQuery = entityManager.createQuery(criteriaQuery);
        typedQuery.setMaxResults(500);
        List<RoleMembershipBean> resultList = typedQuery.getResultList();
        for (RoleMembershipBean membership : resultList) {
            RoleBean role = getRoleInternal(membership.getRoleId());
            String qualifier = membership.getOrganizationId();
            for (PermissionType permission : role.getPermissions()) {
                PermissionBean p = new PermissionBean();
                p.setName(permission);
                p.setOrganizationId(qualifier);
                permissions.add(p);
            }
        }
        return permissions;
    } catch (Throwable t) {
        logger.error(t.getMessage(), t);
        throw new StorageException(t);
    } finally {
        rollbackTx();
    }
}

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

private TypedQuery<Long> createSearchAllByTypeQuery(DateRangeParam theLastUpdated) {
    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));
    List<Predicate> predicates = new ArrayList<Predicate>();
    predicates.add(builder.equal(from.get("myResourceType"), myResourceName));
    predicates.add(builder.isNull(from.get("myDeleted")));

    if (theLastUpdated != null) {
        predicates.addAll(createLastUpdatedPredicates(theLastUpdated, builder, from));
    }//w  w  w.j  a v  a  2  s.  c  o m

    cq.where(toArray(predicates));

    TypedQuery<Long> query = myEntityManager.createQuery(cq);
    return query;
}

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

private void addPredicateId(Set<Long> thePids) {
    if (thePids == null || thePids.isEmpty()) {
        return;/*from   w  ww  .ja v  a  2 s  .  c  om*/
    }

    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));

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

    cq.where(toArray(predicates));

    TypedQuery<Long> q = myEntityManager.createQuery(cq);
    doSetPids(q.getResultList());
}

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

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

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

    List<Predicate> codePredicates = new ArrayList<Predicate>();
    for (IQueryParameterType nextOr : theList) {
        IQueryParameterType theParameter = nextOr;

        Predicate singleCode = createPredicateString(theParameter, 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:com.yunguchang.data.ApplicationRepository.java

public List<TBusApplyinfoEntity> getAllApplications(String coordinatorUserId, String reasonType, String status,
        DateTime startBefore, DateTime startAfter, DateTime endBefore, DateTime endAfter, Integer offset,
        Integer limit, OrderByParam orderByParam, PrincipalExt principalExt) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<TBusApplyinfoEntity> cq = cb.createQuery(TBusApplyinfoEntity.class);
    Root<TBusApplyinfoEntity> applyRoot = cq.from(TBusApplyinfoEntity.class);
    applyRoot.fetch(TBusApplyinfoEntity_.passenger);
    Fetch<TBusApplyinfoEntity, TSysUserEntity> fetchCoordinator = applyRoot
            .fetch(TBusApplyinfoEntity_.coordinator);
    applyRoot.fetch(TBusApplyinfoEntity_.department);
    Fetch<TBusApplyinfoEntity, TBusScheduleRelaEntity> scheduleFetch = applyRoot
            .fetch(TBusApplyinfoEntity_.schedule, JoinType.LEFT);
    scheduleFetch.fetch(TBusScheduleRelaEntity_.senduser, JoinType.LEFT);
    scheduleFetch.fetch(TBusScheduleRelaEntity_.reciveuser, JoinType.LEFT);
    Fetch<TBusScheduleRelaEntity, TBusScheduleCarEntity> fetchScheduleCar = scheduleFetch
            .fetch(TBusScheduleRelaEntity_.scheduleCars, JoinType.LEFT);
    fetchScheduleCar.fetch(TBusScheduleCarEntity_.car, JoinType.LEFT).fetch(TAzCarinfoEntity_.depot,
            JoinType.LEFT);/*from   w w  w  . j a v  a 2 s. com*/
    fetchScheduleCar.fetch(TBusScheduleCarEntity_.driver, JoinType.LEFT).fetch(TRsDriverinfoEntity_.department,
            JoinType.LEFT);
    Predicate predicate = cb.conjunction();
    if (coordinatorUserId != null) {
        Join<TBusApplyinfoEntity, TSysUserEntity> joinCoordinator = (Join<TBusApplyinfoEntity, TSysUserEntity>) fetchCoordinator;
        predicate = cb.and(predicate, cb.equal(joinCoordinator.get(TSysUserEntity_.userid), coordinatorUserId));
    }
    if (reasonType != null) {
        predicate = cb.and(predicate, cb.equal(applyRoot.get(TBusApplyinfoEntity_.reason), reasonType));
    }
    if (status != null) {
        if (status.indexOf(":") < 0) {
            predicate = cb.and(predicate, cb.equal(applyRoot.get(TBusApplyinfoEntity_.status), status));
        } else {
            String[] statusList = status.split(":");
            predicate = cb.and(predicate,
                    applyRoot.get(TBusApplyinfoEntity_.status).in(Arrays.asList(statusList)));
        }
    }

    if (startBefore != null) {
        predicate = cb.and(predicate,
                cb.lessThanOrEqualTo(applyRoot.get(TBusApplyinfoEntity_.begintime), startBefore));
    }

    if (startAfter != null) {
        predicate = cb.and(predicate,
                cb.greaterThanOrEqualTo(applyRoot.get(TBusApplyinfoEntity_.begintime), startAfter));
    }

    if (endBefore != null) {
        predicate = cb.and(predicate,
                cb.lessThanOrEqualTo(applyRoot.get(TBusApplyinfoEntity_.endtime), endBefore));
    }

    if (endAfter != null) {
        predicate = cb.and(predicate,
                cb.greaterThanOrEqualTo(applyRoot.get(TBusApplyinfoEntity_.endtime), endAfter));
    }

    cq.where(predicate);

    List<Order> orders = new ArrayList<>();
    if (orderByParam != null) {
        for (OrderByParam.OrderBy orderBy : orderByParam.getOrderBies()) {
            Order order = null;
            if (orderBy.getFiled().toLowerCase().equals("start".toLowerCase())) {
                order = cb.desc(applyRoot.get(TBusApplyinfoEntity_.begintime));
            }
            if (order != null && !orderBy.isAsc()) {
                order = order.reverse();
            }
            if (order != null) {
                orders.add(order);
            }
        }

    }
    if (orders.size() == 0) {
        cq.orderBy(cb.desc(applyRoot.get(TBusApplyinfoEntity_.begintime)));
    } else {
        cq.orderBy(orders);
    }

    TypedQuery<TBusApplyinfoEntity> query = em.createQuery(cq);

    if (offset != null) {
        query.setFirstResult(offset);
    }
    if (limit != null) {
        query.setMaxResults(limit);
    }

    applySecurityFilter("applications", principalExt);

    return query.getResultList();
}

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

private void addPredicateHas(List<List<? extends IQueryParameterType>> theHasParameters,
        DateRangeParam theLastUpdated) {

    for (List<? extends IQueryParameterType> nextOrList : theHasParameters) {

        StringBuilder valueBuilder = new StringBuilder();
        String targetResourceType = null;
        String owningParameter = null;
        String parameterName = null;
        for (IQueryParameterType nextParam : nextOrList) {
            HasParam next = (HasParam) nextParam;
            if (valueBuilder.length() > 0) {
                valueBuilder.append(',');
            }//from   w  w  w .  ja  v  a 2  s  .  c o  m
            valueBuilder.append(UrlUtil.escape(next.getValueAsQueryToken(myContext)));
            targetResourceType = next.getTargetResourceType();
            owningParameter = next.getOwningFieldName();
            parameterName = next.getParameterName();
        }

        if (valueBuilder.length() == 0) {
            continue;
        }

        String matchUrl = targetResourceType + '?' + UrlUtil.escape(parameterName) + '='
                + valueBuilder.toString();
        RuntimeResourceDefinition targetResourceDefinition;
        try {
            targetResourceDefinition = myContext.getResourceDefinition(targetResourceType);
        } catch (DataFormatException e) {
            throw new InvalidRequestException("Invalid resource type: " + targetResourceType);
        }

        RuntimeSearchParam owningParameterDef = targetResourceDefinition
                .getSearchParam(parameterName.replaceAll("\\..*", ""));
        if (owningParameterDef == null) {
            throw new InvalidRequestException(
                    "Unknown parameter name: " + targetResourceType + ':' + parameterName);
        }

        owningParameterDef = targetResourceDefinition.getSearchParam(owningParameter);
        if (owningParameterDef == null) {
            throw new InvalidRequestException(
                    "Unknown parameter name: " + targetResourceType + ':' + owningParameter);
        }

        Class<? extends IBaseResource> resourceType = targetResourceDefinition.getImplementingClass();
        Set<Long> match = myCallingDao.processMatchUrl(matchUrl, resourceType);
        if (match.isEmpty()) {
            doSetPids(new ArrayList<Long>());
            return;
        }

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

        List<Predicate> predicates = new ArrayList<Predicate>();
        predicates.add(builder.equal(from.get("mySourceResourceType"), targetResourceType));
        predicates.add(from.get("mySourceResourcePid").in(match));
        predicates.add(createResourceLinkPathPredicate(myContext, owningParameter, from, resourceType));
        predicates.add(builder.equal(from.get("myTargetResourceType"), myResourceName));
        createPredicateResourceId(builder, cq, predicates, from.get("myId").as(Long.class));
        createPredicateLastUpdatedForResourceLink(builder, from, predicates);

        cq.where(toArray(predicates));

        TypedQuery<Long> q = myEntityManager.createQuery(cq);
        doSetPids(q.getResultList());
        if (doHaveNoResults()) {
            return;
        }

        return;
    }
}

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

public IBundleProvider search(final SearchParameterMap theParams) {
    myParams = theParams;//w w w.  j a v a 2s .c o  m
    StopWatch w = new StopWatch();

    doInitializeSearch();

    DateRangeParam lu = theParams.getLastUpdated();

    // Collection<Long> loadPids;
    if (theParams.getEverythingMode() != null) {

        Long pid = null;
        if (theParams.get(BaseResource.SP_RES_ID) != null) {
            StringParam idParm = (StringParam) theParams.get(BaseResource.SP_RES_ID).get(0).get(0);
            pid = BaseHapiFhirDao.translateForcedIdToPid(myResourceName, idParm.getValue(), myForcedIdDao);
        }

        if (theParams.containsKey(Constants.PARAM_CONTENT) || theParams.containsKey(Constants.PARAM_TEXT)) {
            List<Long> pids = mySearchDao.everything(myResourceName, theParams);
            if (pids.isEmpty()) {
                return doReturnProvider();
            }

            doSetPids(pids);

        } else {
            CriteriaBuilder builder = myEntityManager.getCriteriaBuilder();
            CriteriaQuery<Tuple> cq = builder.createTupleQuery();
            Root<ResourceTable> from = cq.from(ResourceTable.class);
            List<Predicate> predicates = new ArrayList<Predicate>();
            if (pid != null) {
                predicates.add(builder.equal(from.get("myId"), pid));
            }
            predicates.add(builder.equal(from.get("myResourceType"), myResourceName));
            predicates.add(builder.isNull(from.get("myDeleted")));
            cq.where(builder.and(SearchBuilder.toArray(predicates)));

            Join<Object, Object> join = from.join("myIncomingResourceLinks", JoinType.LEFT);
            cq.multiselect(from.get("myId").as(Long.class), join.get("mySourceResourcePid").as(Long.class));

            TypedQuery<Tuple> query = myEntityManager.createQuery(cq);
            Set<Long> pids = new HashSet<Long>();
            for (Tuple next : query.getResultList()) {
                pids.add(next.get(0, Long.class));
                Long nextLong = next.get(1, Long.class);
                if (nextLong != null) {
                    pids.add(nextLong);
                }
            }
            doSetPids(pids);

        }

    } else if (theParams.isEmpty()) {

        TypedQuery<Long> query = createSearchAllByTypeQuery(lu);
        doSetPids(query.getResultList());

    } else {

        if (mySearchDao == null) {
            if (theParams.containsKey(Constants.PARAM_TEXT)) {
                throw new InvalidRequestException(
                        "Fulltext search is not enabled on this service, can not process parameter: "
                                + Constants.PARAM_TEXT);
            } else if (theParams.containsKey(Constants.PARAM_CONTENT)) {
                throw new InvalidRequestException(
                        "Fulltext search is not enabled on this service, can not process parameter: "
                                + Constants.PARAM_CONTENT);
            }
        } else {
            List<Long> searchResultPids = mySearchDao.search(myResourceName, theParams);
            if (searchResultPids != null) {
                if (searchResultPids.isEmpty()) {
                    return doReturnProvider();
                }
                doSetPids(searchResultPids);
            }
        }

        if (!theParams.isEmpty()) {
            searchForIdsWithAndOr(theParams, lu);
        }

    }

    // // Load _include and _revinclude before filter and sort in everything mode
    // if (theParams.getEverythingMode() != null) {
    // if (theParams.getRevIncludes() != null && theParams.getRevIncludes().isEmpty() == false) {
    // loadPids.addAll(loadReverseIncludes(loadPids, theParams.getRevIncludes(), true,
    // theParams.getEverythingMode()));
    // loadPids.addAll(loadReverseIncludes(loadPids, theParams.getIncludes(), false, theParams.getEverythingMode()));
    // }
    // }

    if (doHaveNoResults()) {
        return doReturnProvider();
    }

    // Handle _lastUpdated
    if (lu != null) {
        filterResourceIdsByLastUpdated(lu);

        if (doHaveNoResults()) {
            return doReturnProvider();
        }
    }

    // Handle sorting if any was provided
    processSort(theParams);

    ourLog.info(" {} on {} in {}ms", new Object[] { myResourceName, theParams, w.getMillisAndRestart() });
    return doReturnProvider();
}