Example usage for org.hibernate.criterion Restrictions conjunction

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

Introduction

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

Prototype

public static Conjunction conjunction() 

Source Link

Document

Group expressions together in a single conjunction (A and B and C...).

Usage

From source file:org.molasdin.wbase.hibernate.cursor.BasicHibernateCursor.java

License:Apache License

private Conjunction populateFilters(Map<String, FilteringMode> matchModes) {
    Conjunction filterCriterion = Restrictions.conjunction();
    if (filters().size() > 0) {
        for (String prop : filters().keySet()) {
            String translated = translateProperty(prop);

            MatchMode mode = matchModes.containsKey(prop) ? toMatchMode(matchModes.get(prop)) : MatchMode.START;
            filterCriterion.add(new FilterCriterion(translated, filters().get(prop).getRight(), mode));
            //                filterCriterion.add(Restrictions.ilike(translated, filters().get(prop).getRight(), MatchMode.START));
        }//w ww .  j a v  a2  s  .  c  o  m
    }
    return filterCriterion;
}

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

License:Open Source License

@SuppressWarnings("unchecked")
public List<Message> getMessages(Integer recipientId, MessageProgramEnrollment enrollment,
        MessageDefDate[] messageDefDates, MessageStatus status) {
    Session session = sessionFactory.getCurrentSession();
    Criteria criteria = session.createCriteria(Message.class).add(Restrictions.eq("attemptStatus", status))
            .createCriteria("schedule").add(Restrictions.eq("recipientId", recipientId))
            .add(Restrictions.eq("enrollment", enrollment));

    Conjunction notMatchMessages = Restrictions.conjunction();
    for (MessageDefDate messageDefDate : messageDefDates) {
        notMatchMessages.add(Restrictions.or(Restrictions.ne("message", messageDefDate.getMessage()),
                Restrictions.ne("scheduledFor", messageDefDate.getDate())));
    }/*  ww w  .j  a  v  a  2s .  c o m*/
    criteria.add(notMatchMessages);

    return criteria.list();
}

From source file:org.mzd.shap.spring.task.JobDaoSpringHibernate.java

License:Open Source License

public Job findUnfinishedById(final Integer jobId) {
    return getHibernateTemplate().execute(new HibernateCallback<Job>() {
        public Job doInHibernate(Session session) throws HibernateException, SQLException {
            return (Job) session.createCriteria(getPersistentClass()).add(Restrictions.idEq(jobId))
                    .add(Restrictions.conjunction().add(Restrictions.ne("status", Status.DONE))
                            .add(Restrictions.ne("status", Status.ERROR)))
                    .uniqueResult();//ww  w.  ja va  2s  .  c o  m
        }
    });
}

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

License:Open Source License

/**
 * Add a result filter to the Criteria//from  www  . j a  v  a  2  s . co  m
 *
 * @param c
 *            Hibernate criteria
 * @param resultFilter
 *            Result filter to add
 * @throws CodedException
 *             If the requested filter is not supported!
 */
@SuppressWarnings("rawtypes")
public static void addResultFilterToCriteria(Criteria c, Filter resultFilter) throws CodedException {
    if (resultFilter instanceof ComparisonFilter) {
        c.add(getCriterionForComparisonFilter((ComparisonFilter) resultFilter));
    } else if (resultFilter instanceof BinaryLogicFilter) {
        BinaryLogicFilter binaryLogicFilter = (BinaryLogicFilter) resultFilter;
        Junction junction = null;
        if (FilterConstants.BinaryLogicOperator.And.equals(binaryLogicFilter.getOperator())) {
            junction = Restrictions.conjunction();
        } else if (FilterConstants.BinaryLogicOperator.Or.equals(binaryLogicFilter.getOperator())) {
            junction = Restrictions.disjunction();
        } else {
            throw new NoApplicableCodeException()
                    .withMessage("The requested binary logic filter operator is invalid!");
        }
        for (Filter<?> filterPredicate : binaryLogicFilter.getFilterPredicates()) {
            if (!(filterPredicate instanceof ComparisonFilter)) {
                throw new NoApplicableCodeException()
                        .withMessage("The requested result filter is not supported!");
            }
            junction.add(getCriterionForComparisonFilter((ComparisonFilter) filterPredicate));
        }
        c.add(junction);
    } else {
        throw new NoApplicableCodeException().withMessage("The requested result filter is not supported!");
    }
}

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

License:Open Source License

/**
 * Creates a {@link Conjunction} for the specified temporal filters.
 * //  w ww  . j a  v  a  2  s.  c om
 * @param temporalFilters
 *            the filters
 * 
 * @return Hibernate temporal filter criterion
 * 
 * @throws UnsupportedTimeException
 *             if the value and property combination is not applicable for
 *             this restriction
 * @throws UnsupportedValueReferenceException
 *             if the {@link TemporalFilter#getValueReference() value
 *             reference} can not be decoded
 * @throws UnsupportedOperatorException
 *             if no restriction definition for the {@link TimeOperator} is
 *             found
 */
public static Criterion filter(Iterable<TemporalFilter> temporalFilters)
        throws UnsupportedTimeException, UnsupportedValueReferenceException, UnsupportedOperatorException {
    Conjunction conjunction = Restrictions.conjunction();
    Collection<Disjunction> disjunctions = getDisjunction(temporalFilters);
    if (disjunctions.size() == 1) {
        return disjunctions.iterator().next();
    }
    for (Disjunction disjunction : disjunctions) {
        conjunction.add(disjunction);
    }
    return conjunction;
}

From source file:org.onecmdb.core.utils.graph.expression.ConstrainGroupExpression.java

License:Open Source License

@Override
public DetachedCriteria getCriteria() {
    DetachedCriteria crit = getParent().getCriteria();
    Junction junction = null;/*from  ww w  .j  a  va 2 s .c  o  m*/
    if (disjunction) {
        junction = Restrictions.disjunction();
    } else {
        junction = Restrictions.conjunction();
    }
    for (Iterator iter = attributeExpressions.iterator(); iter.hasNext();) {
        AttributeExpression aExpr = (AttributeExpression) iter.next();
        DetachedCriteria attrCriteria = aExpr.getCriteria();
        junction.add(
                Property.forName("longId").in(attrCriteria.setProjection(Projections.property("ownerId"))));
    }
    crit.add(junction);

    return (crit);
}

From source file:org.onecmdb.core.utils.graph.handler.QueryHandler.java

License:Open Source License

private Criterion getConstraint2(GraphQuery query, ItemConstraint cons) {
    if (cons instanceof ItemGroupConstraint) {

        ItemGroupConstraint group = (ItemGroupConstraint) cons;
        Junction j = null;/*from www .j av  a 2  s.com*/
        if (group.conjunction()) {
            j = Restrictions.conjunction();
        } else {
            j = Restrictions.disjunction();
        }

        for (Iterator iter = group.fetchConstraints().iterator(); iter.hasNext();) {
            ItemConstraint con = (ItemConstraint) iter.next();
            Criterion criterion = getConstraint2(query, con);
            if (group.conjunction()) {
                if (criterion == null) {
                    return (null);
                }
            }
            if (criterion != null) {
                j.add(criterion);
            }
        }
        return (j);
    }
    if (cons instanceof ItemNotConstraint) {
        ItemConstraint notCons = ((ItemNotConstraint) cons).fetchConstraint();
        if (notCons == null) {
            throw new IllegalArgumentException("ItemNotGroupConstraint must containt a constraint");
        }
        Criterion notCrit = getConstraint2(query, notCons);
        return (Expression.not(notCrit));
    }
    if (cons instanceof RelationConstraint) {
        RelationConstraint rel = (RelationConstraint) cons;
        DetachedCriteria crit = null;
        String direction = null;
        ItemSelector selector = query.findSelector(rel.getSelector());
        if (!(selector instanceof ItemRelationSelector)) {
            throw new IllegalArgumentException(
                    "RelationExpression selector " + rel.getSelector() + " is not a ItemRelationSelection!");
        }

        RelationExpression relExpr = new RelationExpression();

        if (selector instanceof RFCItemRelationSelector) {
            relExpr = new RFCRelationExpression();
        } else if (selector instanceof TransactionRelationSelector) {
            relExpr = new TransactionRelationExpression();
        }

        ItemRelationSelector relSelector = (ItemRelationSelector) selector;
        Criterion relation = null;
        if (rel.isTarget()) {
            if (relSelector.getSourceRange() != null) {
                if (relSelector.getSourceRange().size() == 0) {
                    log.info("RelationConstraint RelationSelector[" + relSelector.getId()
                            + "] SourceRange Empty!");

                    return (null);
                }
                relExpr.setSourceIds(relSelector.getSourceRange());
            } else {
                String srcId = ((ItemRelationSelector) selector).getSource();
                ItemSelector sel = (ItemSelector) query.findSelector(srcId);
                QueryExpression sExpr = getExpression(query, sel);
                if (sExpr.empty) {
                    return (null);
                }
                DetachedCriteria source = sExpr.criteria;
                relExpr.setSource(source);
            }
            relation = relExpr.getSourceCriterion();
            /*
            crit = relExpr.getSourceCriteria();
            relation = Property.forName("longId").in(crit.setProjection(Projections.property("targetId")));
            */
        } else {

            if (relSelector.getTargetRange() != null) {
                if (relSelector.getTargetRange().size() == 0) {
                    log.info("RelationConstraint RelationSelector[" + relSelector.getId()
                            + "] TargetRange Empty!");
                    return (null);
                }
                relExpr.setTargetIds(relSelector.getTargetRange());
                //relation = Property.forName("longId").in(relSelector.getTargetRange());
            } else {
                String trgId = ((ItemRelationSelector) selector).getTarget();
                ItemSelector sel = query.findSelector(trgId);
                QueryExpression tExpr = getExpression(query, sel);
                if (tExpr.empty) {
                    return (null);
                }
                DetachedCriteria target = tExpr.criteria;
                relExpr.setTarget(target);
            }
            relation = relExpr.getTargetCriterion();
            /*
            crit = relExpr.getTargetCriteria();
            relation = Property.forName("longId").in(crit.setProjection(Projections.property("sourceId")));
            */
        }
        log.debug(relation.toString());
        return (relation);
    }

    if (cons instanceof AttributeValueConstraint) {
        AttributeValueConstraint aValue = (AttributeValueConstraint) cons;
        AttributeValueExpression aExpr = new AttributeValueExpression();
        aExpr.setAlias(aValue.getAlias());
        aExpr.setOperation(aValue.getOperation());
        aExpr.setType(aValue.getValueType());
        aExpr.setStringValue(aValue.getValue());

        if (aExpr.isInternal()) {
            return (aExpr.getInternalCriterion());
        }

        DetachedCriteria attr = aExpr.getCriteria();
        return (Property.forName("longId").in(attr.setProjection(Projections.property("ownerId"))));
    }

    if (cons instanceof ItemSecurityConstraint) {
        ItemSecurityConstraint sCon = (ItemSecurityConstraint) cons;

        if (sCon.getGid() != null) {
            return (Property.forName("gid").eq(sCon.getGid()));
        }
        ItemExpression expr = new ItemExpression();
        expr.setAlias(sCon.getGroupName());

        DetachedCriteria gid = expr.getCriteria();
        return (Property.forName("gid").in(gid.setProjection(Projections.property("longId"))));
    }

    if (cons instanceof ItemIdConstraint) {
        ItemIdConstraint idContrain = (ItemIdConstraint) cons;
        if (idContrain.getId() != null) {
            return (Restrictions.idEq(idContrain.getId()));
        }
        if (idContrain.getAlias() != null) {
            return (Property.forName("alias").eq(idContrain.getAlias()));
        }
    }

    if (cons instanceof RFCTargetConstraint) {
        return (Property.forName("targetId").eq(((RFCTargetConstraint) cons).getLongId()));
    }

    if (cons instanceof AttributeSourceRelationConstraint) {
        AttributeSourceRelationConstraint relACons = (AttributeSourceRelationConstraint) cons;
        AttributeValueExpression expr = new AttributeValueExpression();
        expr.setAlias(relACons.getAlias());
        DetachedCriteria crit = expr.getCriteria();
        return (Property.forName("sourceId").in(crit.setProjection(Projections.property("valueAsLong"))));
    }
    log.error("Constraint{" + cons.getClass().getSimpleName() + "] not implemented!");
    return (null);
}

From source file:org.openfaces.component.filter.HibernateCriterionBuilder.java

License:LGPL

/**
 * Used by the <code>build</code> method internally. This method shouldn't normally be invoked by application
 * developers./*from ww  w. ja  v  a2s  .  co m*/
 */
public Object process(AndFilterCriterion criterion) {
    List<FilterCriterion> criteria = criterion.getCriteria();
    Conjunction conjunction = Restrictions.conjunction();
    for (FilterCriterion filterCriterion : criteria) {
        Criterion hibernateCriterion = (Criterion) filterCriterion.process(this);
        conjunction.add(hibernateCriterion);
    }
    return conjunction;
}

From source file:org.openmrs.api.db.hibernate.HibernateEncounterDAO.java

License:Mozilla Public License

/**
 * Utility method that returns a criteria for searching for patient encounters that match the
 * specified search phrase//  www. j  av a2  s  .c  om
 *
 * @param query patient name or identifier
 * @param patientId the patient id
 * @param includeVoided Specifies whether voided encounters should be included
 * @param orderByNames specifies whether the encounters should be ordered by person names
 * @return Criteria
 */
private Criteria createEncounterByQueryCriteria(String query, Integer patientId, boolean includeVoided,
        boolean orderByNames) {
    Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Encounter.class, "enc");
    if (!includeVoided) {
        criteria.add(Restrictions.eq("enc.voided", false));
    }

    criteria = criteria.createCriteria("patient", "pat");
    if (patientId != null) {
        criteria.add(Restrictions.eq("pat.patientId", patientId));
        if (StringUtils.isNotBlank(query)) {
            criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
            //match on location.name, encounterType.name, form.name
            //provider.name, provider.identifier, provider.person.names
            MatchMode mode = MatchMode.ANYWHERE;
            criteria.createAlias("enc.location", "loc");
            criteria.createAlias("enc.encounterType", "encType");
            criteria.createAlias("enc.form", "form");
            criteria.createAlias("enc.encounterProviders", "enc_prov");
            criteria.createAlias("enc_prov.provider", "prov");
            criteria.createAlias("prov.person", "person", Criteria.LEFT_JOIN);
            criteria.createAlias("person.names", "personName", Criteria.LEFT_JOIN);

            Disjunction or = Restrictions.disjunction();
            or.add(Restrictions.ilike("loc.name", query, mode));
            or.add(Restrictions.ilike("encType.name", query, mode));
            or.add(Restrictions.ilike("form.name", query, mode));
            or.add(Restrictions.ilike("prov.name", query, mode));
            or.add(Restrictions.ilike("prov.identifier", query, mode));

            String[] splitNames = query.split(" ");
            Disjunction nameOr = Restrictions.disjunction();
            for (String splitName : splitNames) {
                nameOr.add(Restrictions.ilike("personName.givenName", splitName, mode));
                nameOr.add(Restrictions.ilike("personName.middleName", splitName, mode));
                nameOr.add(Restrictions.ilike("personName.familyName", splitName, mode));
                nameOr.add(Restrictions.ilike("personName.familyName2", splitName, mode));
            }
            //OUTPUT for provider criteria: 
            //prov.name like '%query%' OR prov.identifier like '%query%'
            //OR ( personName.voided = false 
            //       AND (  personName.givenName like '%query%' 
            //         OR personName.middleName like '%query%' 
            //         OR personName.familyName like '%query%'
            //         OR personName.familyName2 like '%query%'
            //         )
            //    )
            Conjunction personNameConjuction = Restrictions.conjunction();
            personNameConjuction.add(Restrictions.eq("personName.voided", false));
            personNameConjuction.add(nameOr);

            or.add(personNameConjuction);

            criteria.add(or);
        }
    } else {
        String name = null;
        String identifier = null;
        if (query.matches(".*\\d+.*")) {
            identifier = query;
        } else {
            // there is no number in the string, search on name
            name = query;
        }
        criteria = new PatientSearchCriteria(sessionFactory, criteria).prepareCriteria(name, identifier,
                new ArrayList<PatientIdentifierType>(), false, orderByNames, false);
    }

    return criteria;
}

From source file:org.openmrs.api.db.hibernate.HibernateProviderDAO.java

License:Mozilla Public License

/**
 * Creates a Provider Criteria based on name
 *
 * @param name represents provider name//from w  w  w .j a v  a 2s . c  om
 * @param includeRetired
 * @return Criteria represents the hibernate criteria to search
 */
private Criteria prepareProviderCriteria(String name, boolean includeRetired) {
    if (StringUtils.isBlank(name)) {
        name = "%";
    }

    Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Provider.class).createAlias("person",
            "p", Criteria.LEFT_JOIN);
    if (!includeRetired) {
        criteria.add(Restrictions.eq("retired", false));
    }

    criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

    criteria.createAlias("p.names", "personName", Criteria.LEFT_JOIN);

    Disjunction or = Restrictions.disjunction();
    or.add(Restrictions.ilike("identifier", name, getMatchMode()));
    or.add(Restrictions.ilike("name", name, MatchMode.ANYWHERE));

    Conjunction and = Restrictions.conjunction();
    or.add(and);

    String[] splitNames = name.split(" ");
    for (String splitName : splitNames) {
        and.add(getNameSearchExpression(splitName));
    }

    criteria.add(or);

    return criteria;
}