Example usage for org.hibernate.criterion Restrictions eqProperty

List of usage examples for org.hibernate.criterion Restrictions eqProperty

Introduction

In this page you can find the example usage for org.hibernate.criterion Restrictions eqProperty.

Prototype

public static PropertyExpression eqProperty(String propertyName, String otherPropertyName) 

Source Link

Document

Apply an "equal" constraint to two properties

Usage

From source file:org.candlepin.auth.permissions.JobStatusPermission.java

License:Open Source License

@Override
@SuppressWarnings("checkstyle:indentation")
public Criterion getCriteriaRestrictions(Class entityClass) {
    if (!entityClass.equals(JobStatus.class)) {
        return null;
    }/*from w  w  w. j  a v a  2 s .c  om*/

    Conjunction conjunction = Restrictions.conjunction();
    // Org has to match.
    conjunction.add(Restrictions.in("ownerId", allowedOrgIds));

    conjunction.add(Restrictions.or(Restrictions.ne("targetType", JobStatus.TargetType.OWNER),
            Restrictions.and(Restrictions.eq("targetType", JobStatus.TargetType.OWNER),
                    Restrictions.eqProperty("ownerId", "targetId"))));

    // If the principal is not a user, make sure to enforce a principalName match.
    if (!"user".equalsIgnoreCase(principalType)) {
        conjunction.add(Restrictions.eq("principalName", principalName));
    }
    return conjunction;
}

From source file:org.candlepin.gutterball.curator.ComplianceSnapshotCurator.java

License:Open Source License

/**
 * Retrieves an iterator over the compliance snapshots on the target date.
 *
 * @param targetDate//  www.  j ava 2s  . co m
 *  The date for which to retrieve compliance snapshots. If null, the current date will be used
 *  instead.
 *
 * @param consumerUuids
 *  A list of consumer UUIDs to use to filter the results. If provided, only compliances for
 *  consumers in the list will be retrieved.
 *
 * @param ownerFilters
 *  A list of owners to use to filter the results. If provided, only compliances for consumers
 *  belonging to the specified owners (orgs) will be retrieved.
 *
 * @param statusFilters
 *  A list of statuses to use to filter the results. If provided, only compliances with a status
 *  matching the list will be retrieved.
 *
 * @param productNameFilters
 *  A list of product names to use to filter compliances. If provided, only compliances for
 *  consumers having installed the specified products will be retrieved.
 *
 * @param subscriptionSkuFilters
 *  A list of subscription skus to use to filter compliances. If provided, only compliances for
 *  the specified subscription skus will be retrieved.
 *
 * @param subscriptionNameFilters
 *  A list of subscription names to use to filter compliances. If provided, only compliances for
 *  the specified subscription names will be retrieved.
 *
 * @param attributeFilters
 *  A map of entitlement attributes to use to filter compliances. If provided, only compliances
 *  for entitlements having the specified values for the given attributes will be retrieved.
 *
 * @param pageRequest
 *  A PageRequest instance containing paging information from the request. If null, no paging
 *  will be performed.
 *
 * @return
 *  A Page instance containing an iterator over the compliance snapshots for the target date and
 *  the paging information for the query.
 */
@SuppressWarnings("checkstyle:indentation")
public Page<Iterator<Compliance>> getSnapshotIterator(Date targetDate, List<String> consumerUuids,
        List<String> ownerFilters, List<String> statusFilters, List<String> productNameFilters,
        List<String> subscriptionSkuFilters, List<String> subscriptionNameFilters,
        Map<String, String> attributeFilters, PageRequest pageRequest) {

    Page<Iterator<Compliance>> page = new Page<Iterator<Compliance>>();
    page.setPageRequest(pageRequest);

    DetachedCriteria subquery = DetachedCriteria.forClass(Compliance.class);
    subquery.createAlias("consumer", "c");
    subquery.createAlias("c.consumerState", "state");

    // https://hibernate.atlassian.net/browse/HHH-2776
    if (consumerUuids != null && !consumerUuids.isEmpty()) {
        subquery.add(Restrictions.in("c.uuid", consumerUuids));
    }

    Date toCheck = targetDate == null ? new Date() : targetDate;
    subquery.add(
            Restrictions.or(Restrictions.isNull("state.deleted"), Restrictions.gt("state.deleted", toCheck)));
    subquery.add(Restrictions.le("state.created", toCheck));

    if (ownerFilters != null && !ownerFilters.isEmpty()) {
        subquery.createAlias("c.owner", "o");
        subquery.add(Restrictions.in("o.key", ownerFilters));
    }

    subquery.add(Restrictions.le("date", toCheck));

    subquery.setProjection(
            Projections.projectionList().add(Projections.max("date")).add(Projections.groupProperty("c.uuid")));

    Session session = this.currentSession();
    Criteria query = session.createCriteria(Compliance.class, "comp").createAlias("comp.consumer", "cs")
            .add(Subqueries.propertiesIn(new String[] { "comp.date", "cs.uuid" }, subquery))
            .setCacheMode(CacheMode.IGNORE).setReadOnly(true);

    if ((statusFilters != null && !statusFilters.isEmpty())
            || (attributeFilters != null && attributeFilters.containsKey("management_enabled"))
            || (productNameFilters != null && !productNameFilters.isEmpty())) {

        query.createAlias("comp.status", "stat");

        if (statusFilters != null && !statusFilters.isEmpty()) {
            query.add(Restrictions.in("stat.status", statusFilters));
        }

        if (attributeFilters != null && attributeFilters.containsKey("management_enabled")) {
            boolean managementEnabledFilter = PropertyConverter
                    .toBoolean(attributeFilters.get("management_enabled"));
            query.add(Restrictions.eq("stat.managementEnabled", managementEnabledFilter));
        }

        if (productNameFilters != null && !productNameFilters.isEmpty()) {
            query.createAlias("stat.compliantProducts", "cprod", JoinType.LEFT_OUTER_JOIN)
                    .createAlias("stat.partiallyCompliantProducts", "pcprod", JoinType.LEFT_OUTER_JOIN)
                    .createAlias("stat.nonCompliantProducts", "ncprod", JoinType.LEFT_OUTER_JOIN);

            DetachedCriteria prodQuery = DetachedCriteria.forClass(Compliance.class, "comp2");
            prodQuery.createAlias("comp2.consumer", "cons2");
            prodQuery.createAlias("cons2.installedProducts", "installed");
            prodQuery.add(Restrictions.and(Restrictions.in("installed.productName", productNameFilters),
                    Restrictions.eqProperty("comp2.id", "comp.id")));
            prodQuery.setProjection(Projections.property("installed.productId"));

            query.add(Restrictions.or(Property.forName("cprod.productId").in(prodQuery),
                    Property.forName("pcprod.productId").in(prodQuery),
                    Property.forName("ncprod.productId").in(prodQuery)));
        }
    }

    // Add subscription filters, if necessary
    if ((subscriptionSkuFilters != null && !subscriptionSkuFilters.isEmpty())
            || (subscriptionNameFilters != null && !subscriptionNameFilters.isEmpty())) {

        // Impl note: We have to be very careful with alias names, as Hibernate has a tendancy
        // to errorneously truncate "long" ones. Actual property/field names are safe, though.
        query.createAlias("comp.entitlements", "entsnap");

        if (subscriptionSkuFilters != null && !subscriptionSkuFilters.isEmpty()) {
            query.add(Restrictions.in("entsnap.productId", subscriptionSkuFilters));
        }

        if (subscriptionNameFilters != null && !subscriptionNameFilters.isEmpty()) {
            query.add(Restrictions.in("entsnap.productName", subscriptionNameFilters));
        }
    }

    if (pageRequest != null && pageRequest.isPaging()) {
        page.setMaxRecords(this.getRowCount(query));

        query.setFirstResult((pageRequest.getPage() - 1) * pageRequest.getPerPage());
        query.setMaxResults(pageRequest.getPerPage());

        if (pageRequest.getSortBy() != null) {
            query.addOrder(
                    pageRequest.getOrder() == PageRequest.Order.ASCENDING ? Order.asc(pageRequest.getSortBy())
                            : Order.desc(pageRequest.getSortBy()));
        }
    }

    page.setPageData(new AutoEvictingColumnarResultsIterator<Compliance>(session,
            query.scroll(ScrollMode.FORWARD_ONLY), 0));

    return page;
}

From source file:org.candlepin.gutterball.curator.ComplianceSnapshotCurator.java

License:Open Source License

/**
 * Retrieves an iterator over the compliance snapshots for the specified consumer.
 *
 * @param consumerUUID//from  w w  w .ja v  a  2 s  .c o m
 *  The UUID for the consumer for which to retrieve compliance snapshots.
 *
 * @param startDate
 *  The start date to use to filter snapshots retrieved. If specified, only snapshots occurring
 *  after the start date, and the snapshot immediately preceding it, will be retrieved.
 *
 * @param endDate
 *  The end date to use to filter snapshots retrieved. If specified, only snapshots occurring
 *  before the end date will be retrieved.
 *
 * @param pageRequest
 *  A PageRequest instance containing paging information from the request. If null, no paging
 *  will be performed.
 *
 * @return
 *  A Page instance containing an iterator over the snapshots for the specified consumer, and
 *  the paging information for the query.
 */
@SuppressWarnings("checkstyle:indentation")
public Page<Iterator<Compliance>> getSnapshotIteratorForConsumer(String consumerUUID, Date startDate,
        Date endDate, PageRequest pageRequest) {

    Page<Iterator<Compliance>> page = new Page<Iterator<Compliance>>();
    page.setPageRequest(pageRequest);

    Session session = this.currentSession();
    Criteria query = session.createCriteria(Compliance.class, "comp1");
    query.createAlias("comp1.consumer", "cons1");

    query.add(Restrictions.eq("cons1.uuid", consumerUUID));

    if (startDate != null) {
        DetachedCriteria subquery = DetachedCriteria.forClass(Compliance.class, "comp2");
        subquery.createAlias("comp2.consumer", "cons2");
        subquery.createAlias("cons2.consumerState", "state2");

        subquery.add(Restrictions.or(Restrictions.isNull("state2.deleted"),
                Restrictions.gt("state2.deleted", startDate)));

        subquery.add(Restrictions.lt("state2.created", startDate));
        subquery.add(Restrictions.eqProperty("cons2.uuid", "cons1.uuid"));
        subquery.add(Restrictions.lt("comp2.date", startDate));

        subquery.setProjection(Projections.projectionList().add(Projections.max("comp2.date")));

        query.add(Restrictions.disjunction().add(Restrictions.ge("comp1.date", startDate))
                .add(Subqueries.propertyEq("comp1.date", subquery)));
    }

    if (endDate != null) {
        query.add(Restrictions.le("comp1.date", endDate));
    }

    query.setCacheMode(CacheMode.IGNORE);
    query.setReadOnly(true);

    if (pageRequest != null && pageRequest.isPaging()) {
        page.setMaxRecords(this.getRowCount(query));

        query.setFirstResult((pageRequest.getPage() - 1) * pageRequest.getPerPage());
        query.setMaxResults(pageRequest.getPerPage());

        if (pageRequest.getSortBy() != null) {
            query.addOrder(
                    pageRequest.getOrder() == PageRequest.Order.ASCENDING ? Order.asc(pageRequest.getSortBy())
                            : Order.desc(pageRequest.getSortBy()));
        }
    }

    page.setPageData(new AutoEvictingColumnarResultsIterator<Compliance>(session,
            query.scroll(ScrollMode.FORWARD_ONLY), 0));

    return page;
}

From source file:org.candlepin.model.FactFilterBuilder.java

License:Open Source License

@Override
protected Criterion buildCriteriaForKey(String key, List<String> values) {
    Disjunction valuesCriteria = Restrictions.disjunction();
    for (String value : values) {
        if (StringUtils.isEmpty(value)) {
            valuesCriteria.add(Restrictions.isNull("cfacts.elements"));
            valuesCriteria.add(Restrictions.eq("cfacts.elements", ""));
        } else {/*from  w ww  . j a  v  a2  s.co  m*/
            valuesCriteria.add(new FactLikeExpression("cfacts.elements", value, true));
        }
    }

    DetachedCriteria dc = DetachedCriteria.forClass(Consumer.class, "subcons")
            .add(Restrictions.eqProperty("this.id", "subcons.id")).createAlias("subcons.facts", "cfacts")
            // Match the key, case sensitive
            .add(new FactLikeExpression("cfacts.indices", key, false))
            // Match values, case insensitive
            .add(valuesCriteria).setProjection(Projections.property("subcons.id"));

    return Subqueries.exists(dc);
}

From source file:org.codehaus.groovy.grails.orm.hibernate.query.AbstractHibernateCriterionAdapter.java

License:Apache License

protected void addPropertyComparisonCriterionAdapters() {
    criterionAdaptors.put(Query.EqualsProperty.class, new CriterionAdaptor<Query.EqualsProperty>() {
        @Override// w  ww .j  a  v a  2s .  c  om
        public Criterion toHibernateCriterion(AbstractHibernateQuery hibernateQuery,
                Query.EqualsProperty criterion, String alias) {
            String propertyName = getPropertyName(criterion, alias);
            return Restrictions.eqProperty(propertyName, criterion.getOtherProperty());
        }
    });
    criterionAdaptors.put(Query.GreaterThanProperty.class, new CriterionAdaptor<Query.GreaterThanProperty>() {
        @Override
        public Criterion toHibernateCriterion(AbstractHibernateQuery hibernateQuery,
                Query.GreaterThanProperty criterion, String alias) {
            String propertyName = getPropertyName(criterion, alias);
            return Restrictions.gtProperty(propertyName, criterion.getOtherProperty());
        }
    });
    criterionAdaptors.put(Query.GreaterThanEqualsProperty.class,
            new CriterionAdaptor<Query.GreaterThanEqualsProperty>() {
                @Override
                public Criterion toHibernateCriterion(AbstractHibernateQuery hibernateQuery,
                        Query.GreaterThanEqualsProperty criterion, String alias) {
                    String propertyName = getPropertyName(criterion, alias);
                    return Restrictions.geProperty(propertyName, criterion.getOtherProperty());
                }
            });
    criterionAdaptors.put(Query.LessThanProperty.class, new CriterionAdaptor<Query.LessThanProperty>() {
        @Override
        public Criterion toHibernateCriterion(AbstractHibernateQuery hibernateQuery,
                Query.LessThanProperty criterion, String alias) {
            String propertyName = getPropertyName(criterion, alias);
            return Restrictions.ltProperty(propertyName, criterion.getOtherProperty());
        }
    });
    criterionAdaptors.put(Query.LessThanEqualsProperty.class,
            new CriterionAdaptor<Query.LessThanEqualsProperty>() {
                @Override
                public Criterion toHibernateCriterion(AbstractHibernateQuery hibernateQuery,
                        Query.LessThanEqualsProperty criterion, String alias) {
                    String propertyName = getPropertyName(criterion, alias);
                    return Restrictions.leProperty(propertyName, criterion.getOtherProperty());
                }
            });
    criterionAdaptors.put(Query.NotEqualsProperty.class, new CriterionAdaptor<Query.NotEqualsProperty>() {
        @Override
        public Criterion toHibernateCriterion(AbstractHibernateQuery hibernateQuery,
                Query.NotEqualsProperty criterion, String alias) {
            String propertyName = getPropertyName(criterion, alias);
            return Restrictions.neProperty(propertyName, criterion.getOtherProperty());
        }
    });
}

From source file:org.dspace.content.dao.impl.ItemDAOImpl.java

License:BSD License

@Override
public Iterator<Item> findByMetadataQuery(Context context, List<List<MetadataField>> listFieldList,
        List<String> query_op, List<String> query_val, List<UUID> collectionUuids, String regexClause,
        int offset, int limit) throws SQLException {
    Criteria criteria = createCriteria(context, Item.class, "item");
    criteria.setFirstResult(offset);//from www  .  ja  va  2 s.  c  o m
    criteria.setMaxResults(limit);

    if (!collectionUuids.isEmpty()) {
        DetachedCriteria dcollCriteria = DetachedCriteria.forClass(Collection.class, "coll");
        dcollCriteria.setProjection(Projections.property("coll.id"));
        dcollCriteria.add(Restrictions.eqProperty("coll.id", "item.owningCollection"));
        dcollCriteria.add(Restrictions.in("coll.id", collectionUuids));
        criteria.add(Subqueries.exists(dcollCriteria));
    }

    int index = Math.min(listFieldList.size(), Math.min(query_op.size(), query_val.size()));
    StringBuilder sb = new StringBuilder();

    for (int i = 0; i < index; i++) {
        OP op = OP.valueOf(query_op.get(i));
        if (op == null) {
            log.warn("Skipping Invalid Operator: " + query_op.get(i));
            continue;
        }

        if (op == OP.matches || op == OP.doesnt_match) {
            if (regexClause.isEmpty()) {
                log.warn("Skipping Unsupported Regex Operator: " + query_op.get(i));
                continue;
            }
        }

        DetachedCriteria subcriteria = DetachedCriteria.forClass(MetadataValue.class, "mv");
        subcriteria.add(Property.forName("mv.dSpaceObject").eqProperty("item.id"));
        subcriteria.setProjection(Projections.property("mv.dSpaceObject"));

        if (!listFieldList.get(i).isEmpty()) {
            subcriteria.add(Restrictions.in("metadataField", listFieldList.get(i)));
        }

        sb.append(op.name() + " ");
        if (op == OP.equals || op == OP.not_equals) {
            subcriteria.add(Property.forName("mv.value").eq(query_val.get(i)));
            sb.append(query_val.get(i));
        } else if (op == OP.like || op == OP.not_like) {
            subcriteria.add(Property.forName("mv.value").like(query_val.get(i)));
            sb.append(query_val.get(i));
        } else if (op == OP.contains || op == OP.doesnt_contain) {
            subcriteria.add(Property.forName("mv.value").like("%" + query_val.get(i) + "%"));
            sb.append(query_val.get(i));
        } else if (op == OP.matches || op == OP.doesnt_match) {
            subcriteria
                    .add(Restrictions.sqlRestriction(regexClause, query_val.get(i), StandardBasicTypes.STRING));
            sb.append(query_val.get(i));
        }

        if (op == OP.exists || op == OP.equals || op == OP.like || op == OP.contains || op == OP.matches) {
            criteria.add(Subqueries.exists(subcriteria));
        } else {
            criteria.add(Subqueries.notExists(subcriteria));
        }
    }
    log.debug(String.format("Running custom query with %d filters", index));

    return list(criteria).iterator();
}

From source file:org.fornax.cartridges.sculptor.framework.accessimpl.jpahibernate.JpaHibFindByConditionAccessImpl.java

License:Apache License

private Criterion makeCriterion(ConditionalCriteria crit) {
    if (crit == null) {
        return null;
    }/*from w  ww .  ja  v  a 2s .c om*/

    ConditionalCriteria.Operator operator = crit.getOperator();
    if (Operator.Equal.equals(operator)) {
        return Restrictions.eq(makePathWithAlias(crit.getPropertyFullName()), crit.getFirstOperant());
    } else if (Operator.IgnoreCaseEqual.equals(operator)) {
        return Restrictions.eq(makePathWithAlias(crit.getPropertyFullName()), crit.getFirstOperant())
                .ignoreCase();
    } else if (Operator.LessThan.equals(operator)) {
        return Restrictions.lt(makePathWithAlias(crit.getPropertyFullName()), crit.getFirstOperant());
    } else if (Operator.LessThanOrEqual.equals(operator)) {
        return Restrictions.le(makePathWithAlias(crit.getPropertyFullName()), crit.getFirstOperant());
    } else if (Operator.GreatThan.equals(operator)) {
        return Restrictions.gt(makePathWithAlias(crit.getPropertyFullName()), crit.getFirstOperant());
    } else if (Operator.GreatThanOrEqual.equals(operator)) {
        return Restrictions.ge(makePathWithAlias(crit.getPropertyFullName()), crit.getFirstOperant());
    } else if (Operator.Like.equals(operator)) {
        return Restrictions.like(makePathWithAlias(crit.getPropertyFullName()), crit.getFirstOperant());
    } else if (Operator.IgnoreCaseLike.equals(operator)) {
        return Restrictions.ilike(makePathWithAlias(crit.getPropertyFullName()), crit.getFirstOperant());
    } else if (Operator.IsNull.equals(operator)) {
        return Restrictions.isNull(makePathWithAlias(crit.getPropertyFullName()));
    } else if (Operator.IsNotNull.equals(operator)) {
        return Restrictions.isNotNull(makePathWithAlias(crit.getPropertyFullName()));
    } else if (Operator.IsEmpty.equals(operator)) {
        return Restrictions.isEmpty(makePathWithAlias(crit.getPropertyFullName()));
    } else if (Operator.IsNotEmpty.equals(operator)) {
        return Restrictions.isNotEmpty(makePathWithAlias(crit.getPropertyFullName()));
    } else if (Operator.Not.equals(operator)) {
        return Restrictions.not(makeCriterion((ConditionalCriteria) crit.getFirstOperant()));
    } else if (Operator.Or.equals(operator) && crit.getFirstOperant() instanceof List<?>) {
        Disjunction disj = Restrictions.disjunction();
        List<?> disjList = (List<?>) crit.getFirstOperant();
        for (Object disjPart : disjList) {
            disj.add(makeCriterion((ConditionalCriteria) disjPart));
        }
        return disj;
    } else if (Operator.Or.equals(operator)) {
        return Restrictions.or(makeCriterion((ConditionalCriteria) crit.getFirstOperant()),
                makeCriterion((ConditionalCriteria) crit.getSecondOperant()));
    } else if (Operator.And.equals(operator) && crit.getFirstOperant() instanceof List<?>) {
        Conjunction conj = Restrictions.conjunction();
        List<?> conjList = (List<?>) crit.getFirstOperant();
        for (Object conjPart : conjList) {
            conj.add(makeCriterion((ConditionalCriteria) conjPart));
        }
        return conj;
    } else if (Operator.And.equals(operator)) {
        return Restrictions.and(makeCriterion((ConditionalCriteria) crit.getFirstOperant()),
                makeCriterion((ConditionalCriteria) crit.getSecondOperant()));
    } else if (Operator.In.equals(operator)) {
        if (crit.getFirstOperant() instanceof Collection<?>) {
            return Restrictions.in(makePathWithAlias(crit.getPropertyFullName()),
                    (Collection<?>) crit.getFirstOperant());
        } else {
            return Restrictions.in(makePathWithAlias(crit.getPropertyFullName()),
                    (Object[]) crit.getFirstOperant());
        }
    } else if (Operator.Between.equals(operator)) {
        return Restrictions.between(makePathWithAlias(crit.getPropertyFullName()), crit.getFirstOperant(),
                crit.getSecondOperant());
    } else if (Operator.DistinctRoot.equals(operator)) {
        realDistinctRoot = true;
        return null;
    } else if (Operator.ProjectionRoot.equals(operator)) {
        resultTransformer = Criteria.PROJECTION;
        return null;
    } else if (Operator.EqualProperty.equals(operator)) {
        return Restrictions.eqProperty(makePathWithAlias(crit.getPropertyFullName()),
                (String) crit.getFirstOperant());
    } else if (Operator.LessThanProperty.equals(operator)) {
        return Restrictions.eqProperty(makePathWithAlias(crit.getPropertyFullName()),
                (String) crit.getFirstOperant());
    } else if (Operator.LessThanOrEqualProperty.equals(operator)) {
        return Restrictions.eqProperty(makePathWithAlias(crit.getPropertyFullName()),
                (String) crit.getFirstOperant());
    } else if (Operator.GreatThanProperty.equals(operator)) {
        return Restrictions.eqProperty(makePathWithAlias(crit.getPropertyFullName()),
                (String) crit.getFirstOperant());
    } else if (Operator.GreatThanOrEqualProperty.equals(operator)) {
        return Restrictions.eqProperty(makePathWithAlias(crit.getPropertyFullName()),
                (String) crit.getFirstOperant());
    } else {
        return null;
    }
}

From source file:org.motechproject.server.model.db.hibernate.HibernateMotechDAO.java

License:Open Source License

@SuppressWarnings("unchecked")
public List<Obs> getActivePregnanciesDueDateObs(Facility facility, Date fromDueDate, Date toDueDate,
        Concept pregnancyDueDateConcept, Concept pregnancyConcept, Concept pregnancyStatusConcept,
        Integer maxResults) {/*  w w  w.  j  a v  a2s  . c  o m*/
    Session session = sessionFactory.getCurrentSession();
    Criteria criteria = session.createCriteria(Obs.class, "o");

    criteria.add(Restrictions.eq("o.voided", false));
    criteria.add(Restrictions.eq("o.concept", pregnancyDueDateConcept));

    if (fromDueDate != null) {
        criteria.add(Restrictions.ge("o.valueDatetime", fromDueDate));
    }
    if (toDueDate != null) {
        criteria.add(Restrictions.le("o.valueDatetime", toDueDate));
    }

    criteria.createAlias("o.person", "p");
    criteria.add(Restrictions.eq("p.personVoided", false));

    criteria.createAlias("o.obsGroup", "g");
    criteria.add(Restrictions.eq("g.concept", pregnancyConcept));
    criteria.add(Restrictions.eq("g.voided", false));

    DetachedCriteria pregnancyActiveCriteria = DetachedCriteria.forClass(Obs.class, "s")
            .setProjection(Projections.id()).add(Restrictions.eq("s.voided", false))
            .add(Restrictions.eq("s.concept", pregnancyStatusConcept))
            .add(Restrictions.eq("s.valueNumeric", 1.0))
            .add(Restrictions.eqProperty("s.obsGroup.obsId", "g.obsId"))
            .add(Restrictions.eqProperty("s.person.personId", "p.personId"));

    criteria.add(Subqueries.exists(pregnancyActiveCriteria));

    DetachedCriteria pregnancyInactiveCriteria = DetachedCriteria.forClass(Obs.class, "e")
            .setProjection(Projections.id()).add(Restrictions.eq("e.voided", false))
            .add(Restrictions.eq("e.concept", pregnancyStatusConcept))
            .add(Restrictions.eq("e.valueNumeric", 0.0))
            .add(Restrictions.eqProperty("e.obsGroup.obsId", "g.obsId"))
            .add(Restrictions.eqProperty("e.person.personId", "p.personId"));

    criteria.add(Subqueries.notExists(pregnancyInactiveCriteria));

    if (facility != null) {
        criteria.add(Restrictions.sqlRestriction(
                "exists (select f.id from motechmodule_facility f "
                        + "inner join motechmodule_facility_patient fp " + "on f.id = fp.facility_id "
                        + "where f.facility_id = ? and fp.patient_id = {alias}.person_id)",
                facility.getFacilityId(), Hibernate.INTEGER));
    }

    criteria.addOrder(Order.asc("o.valueDatetime"));
    if (maxResults != null) {
        criteria.setMaxResults(maxResults);
    }
    return criteria.list();
}

From source file:org.motechproject.server.model.db.hibernate.HibernateMotechDAO.java

License:Open Source License

@SuppressWarnings("unchecked")
public List<Patient> getPatients(String firstName, String lastName, String preferredName, Date birthDate,
        Integer facilityId, String phoneNumber, PersonAttributeType phoneNumberAttrType, String nhisNumber,
        PersonAttributeType nhisAttrType, Integer communityId, String patientId,
        PatientIdentifierType patientIdType, Integer maxResults) {

    Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Patient.class, "p");

    criteria.createAlias("p.names", "name");
    criteria.createAlias("p.identifiers", "id");

    criteria.add(Restrictions.eq("p.voided", false));
    criteria.add(Restrictions.eq("name.voided", false));
    criteria.add(Restrictions.eq("id.voided", false));

    if (patientId != null && patientIdType != null) {
        criteria.add(Restrictions.and(Restrictions.eq("id.identifierType", patientIdType),
                Restrictions.eq("id.identifier", patientId)));
    }//from ww  w  . j  ava 2  s.  c  o m

    Criterion firstNameCriterion = Restrictions.like("name.givenName", firstName, MatchMode.ANYWHERE);
    Criterion preferredNameCriterion = Restrictions.like("name.givenName", preferredName, MatchMode.ANYWHERE);
    if (firstName != null && preferredName != null) {
        criteria.add(Restrictions.or(firstNameCriterion, preferredNameCriterion));
    } else if (firstName != null) {
        criteria.add(firstNameCriterion);
    } else if (preferredName != null) {
        criteria.add(preferredNameCriterion);
    }

    if (lastName != null) {
        criteria.add(Restrictions.like("name.familyName", lastName, MatchMode.ANYWHERE));
    }

    if (birthDate != null) {
        criteria.add(Restrictions.eq("p.birthdate", birthDate));
    }

    if (facilityId != null) {
        criteria.add(Restrictions.sqlRestriction(
                "exists (select f.id from motechmodule_facility f "
                        + "inner join motechmodule_facility_patient fp " + "on f.id = fp.facility_id "
                        + "where f.facility_id = ? and fp.patient_id = {alias}.patient_id)",
                facilityId, Hibernate.INTEGER));
    }

    if (communityId != null) {
        criteria.add(Restrictions.sqlRestriction(
                "exists (select c.id from motechmodule_community c "
                        + "inner join motechmodule_community_patient cp " + "on c.id = cp.community_id "
                        + "where c.community_id = ? and cp.patient_id = {alias}.patient_id)",
                communityId, Hibernate.INTEGER));
    }

    if (nhisNumber != null && nhisAttrType != null) {
        DetachedCriteria nhisCriteria = DetachedCriteria.forClass(PersonAttribute.class, "nattr")
                .setProjection(Projections.id()).add(Restrictions.eq("nattr.voided", false))
                .add(Restrictions.eqProperty("nattr.person.personId", "p.patientId"))
                .add(Restrictions.and(Restrictions.eq("nattr.attributeType", nhisAttrType),
                        Restrictions.eq("nattr.value", nhisNumber)));

        criteria.add(Subqueries.exists(nhisCriteria));
    }

    if (phoneNumber != null && phoneNumberAttrType != null) {
        DetachedCriteria phoneCriteria = DetachedCriteria.forClass(PersonAttribute.class, "pattr")
                .setProjection(Projections.id()).add(Restrictions.eq("pattr.voided", false))
                .add(Restrictions.eqProperty("pattr.person.personId", "p.patientId"))
                .add(Restrictions.and(Restrictions.eq("pattr.attributeType", phoneNumberAttrType),
                        Restrictions.eq("pattr.value", phoneNumber)));

        criteria.add(Subqueries.exists(phoneCriteria));
    }

    criteria.addOrder(Order.asc("name.givenName"));
    criteria.addOrder(Order.asc("name.familyName"));
    criteria.addOrder(Order.asc("p.birthdate"));

    criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
    if (maxResults != null) {
        criteria.setMaxResults(maxResults);
    }
    return criteria.list();
}

From source file:org.n52.sos.ds.hibernate.util.TemporalRestriction.java

License:Open Source License

/**
 * Creates a <tt>Criterion</tt> that checks that the persisted period is a
 * instant period (<tt>begin == end</tt>).
 * //from  ww  w  . ja  v a  2s. c  o  m
 * @param r
 *            the property names
 * 
 * @return the <tt>Criterion</tt>
 */
protected PropertyExpression isInstant(TimePrimitiveFieldDescriptor r) {
    return Restrictions.eqProperty(r.getBeginPosition(), r.getEndPosition());
}