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.openbravo.advpaymentmngt.dao.AdvPaymentMngtDao.java

License:Open Source License

public List<FIN_FinancialAccount> getFilteredFinancialAccounts(String strPaymentMethodId, String strOrgId,
        String strCurrencyId, PaymentDirection paymentDirection) {
    final OBCriteria<FIN_FinancialAccount> obc = OBDal.getInstance().createCriteria(FIN_FinancialAccount.class,
            "acc");
    obc.add(Restrictions.in("organization.id",
            OBContext.getOBContext().getOrganizationStructureProvider().getNaturalTree(strOrgId)));
    obc.setFilterOnReadableOrganization(false);

    Currency requiredCurrency = null;
    if (strCurrencyId != null && !strCurrencyId.isEmpty()) {
        DetachedCriteria multiCurrAllowed = DetachedCriteria
                .forEntityName(FinAccPaymentMethod.ENTITY_NAME, "fapm")
                .add(Restrictions.eqProperty(FinAccPaymentMethod.PROPERTY_ACCOUNT + ".id", "acc.id"));
        if (paymentDirection == PaymentDirection.IN || paymentDirection == PaymentDirection.EITHER) {
            multiCurrAllowed.add(Restrictions.eq(FinAccPaymentMethod.PROPERTY_PAYINISMULTICURRENCY, true));
        }/*ww w  .  j  a v a  2s  .  c o m*/
        if (paymentDirection == PaymentDirection.OUT || paymentDirection == PaymentDirection.EITHER) {
            multiCurrAllowed.add(Restrictions.eq(FinAccPaymentMethod.PROPERTY_PAYOUTISMULTICURRENCY, true));
        }
        requiredCurrency = OBDal.getInstance().get(Currency.class, strCurrencyId);
        obc.add(Restrictions.or(Restrictions.eq(FIN_FinancialAccount.PROPERTY_CURRENCY, requiredCurrency),
                Subqueries.exists(multiCurrAllowed.setProjection(Projections.id()))));
    }

    if (strPaymentMethodId != null && !strPaymentMethodId.isEmpty()) {
        List<FinAccPaymentMethod> finAccsMethods = getObject(FIN_PaymentMethod.class, strPaymentMethodId)
                .getFinancialMgmtFinAccPaymentMethodList();

        if (finAccsMethods.isEmpty()) {
            return (new ArrayList<FIN_FinancialAccount>());
        }
        ExpressionForFinAccPayMethod exp = new ExpressionForFinAccPayMethod();

        for (FinAccPaymentMethod finAccPayMethod : finAccsMethods) {
            boolean validPaymentDirection = true;
            if (paymentDirection == PaymentDirection.IN) {
                validPaymentDirection = finAccPayMethod.isPayinAllow();
            } else if (paymentDirection == PaymentDirection.OUT) {
                validPaymentDirection = finAccPayMethod.isPayoutAllow();
            }

            boolean validCurrency = true;
            if (requiredCurrency != null) {
                boolean multiCurrencyAllowed = false;
                if (paymentDirection == PaymentDirection.IN) {
                    multiCurrencyAllowed = finAccPayMethod.isPayinIsMulticurrency();
                } else if (paymentDirection == PaymentDirection.OUT) {
                    multiCurrencyAllowed = finAccPayMethod.isPayoutIsMulticurrency();
                } else if (paymentDirection == PaymentDirection.EITHER) {
                    multiCurrencyAllowed = finAccPayMethod.isPayinIsMulticurrency()
                            || finAccPayMethod.isPayoutIsMulticurrency();
                }

                validCurrency = multiCurrencyAllowed
                        || requiredCurrency.equals(finAccPayMethod.getAccount().getCurrency());
            }

            if (validPaymentDirection && validCurrency) {
                exp.addFinAccPaymentMethod(finAccPayMethod);
            }

        }

        Criterion crit = exp.getCriterion();
        if (crit != null) {
            obc.add(crit);
        } else {
            return new ArrayList<FIN_FinancialAccount>();
        }
    }
    return obc.list();
}

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

License:Mozilla Public License

/**
 * Convenience method to create the same hibernate criteria object for both getForms and
 * getFormCount/*from   www.  java  2  s  .co  m*/
 *
 * @param partialName
 * @param published
 * @param encounterTypes
 * @param retired
 * @param containingAnyFormField
 * @param containingAllFormFields
 * @param fields
 * @return
 */
private Criteria getFormCriteria(String partialName, Boolean published,
        Collection<EncounterType> encounterTypes, Boolean retired, Collection<FormField> containingAnyFormField,
        Collection<FormField> containingAllFormFields, Collection<Field> fields) {

    Criteria crit = sessionFactory.getCurrentSession().createCriteria(Form.class, "form");

    if (StringUtils.isNotEmpty(partialName)) {
        crit.add(Restrictions.or(Restrictions.like("name", partialName, MatchMode.START),
                Restrictions.like("name", " " + partialName, MatchMode.ANYWHERE)));
    }
    if (published != null) {
        crit.add(Restrictions.eq("published", published));
    }

    if (!encounterTypes.isEmpty()) {
        crit.add(Restrictions.in("encounterType", encounterTypes));
    }

    if (retired != null) {
        crit.add(Restrictions.eq("retired", retired));
    }

    // TODO junit test
    if (!containingAnyFormField.isEmpty()) {
        // Convert form field persistents to integers
        Set<Integer> anyFormFieldIds = new HashSet<Integer>();
        for (FormField ff : containingAnyFormField) {
            anyFormFieldIds.add(ff.getFormFieldId());
        }

        DetachedCriteria subquery = DetachedCriteria.forClass(FormField.class, "ff");
        subquery.setProjection(Projections.property("ff.form.formId"));
        subquery.add(Restrictions.in("ff.formFieldId", anyFormFieldIds));
        crit.add(Subqueries.propertyIn("form.formId", subquery));
    }

    //select * from form where len(containingallformfields) = (select count(*) from form_field ff where ff.form_id = form_id and form_field_id in (containingallformfields);
    if (!containingAllFormFields.isEmpty()) {

        // Convert form field persistents to integers
        Set<Integer> allFormFieldIds = new HashSet<Integer>();
        for (FormField ff : containingAllFormFields) {
            allFormFieldIds.add(ff.getFormFieldId());
        }
        DetachedCriteria subquery = DetachedCriteria.forClass(FormField.class, "ff");
        subquery.setProjection(Projections.count("ff.formFieldId"));
        subquery.add(Restrictions.eqProperty("ff.form", "form"));
        subquery.add(Restrictions.in("ff.formFieldId", allFormFieldIds));

        crit.add(Subqueries.eq(Long.valueOf(containingAllFormFields.size()), subquery));
    }

    // get all forms (dupes included) that have this field on them
    if (!fields.isEmpty()) {
        Criteria crit2 = crit.createCriteria("formFields", "ff");
        crit2.add(Restrictions.eqProperty("ff.form.formId", "form.formId"));
        crit2.add(Restrictions.in("ff.field", fields));
    }

    return crit;
}

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

License:Mozilla Public License

/**
 * @see org.openmrs.api.db.LocationDAO#getLocationsHavingAllTags(java.util.List)
 *///from w w w.  j a v  a2s  .  com
@Override
public List<Location> getLocationsHavingAllTags(List<LocationTag> tags) {
    tags.removeAll(Collections.singleton(null));

    DetachedCriteria numberOfMatchingTags = DetachedCriteria.forClass(Location.class, "alias")
            .createAlias("alias.tags", "locationTag")
            .add(Restrictions.in("locationTag.locationTagId", getLocationTagIds(tags)))
            .setProjection(Projections.rowCount())
            .add(Restrictions.eqProperty("alias.locationId", "outer.locationId"));

    return sessionFactory.getCurrentSession().createCriteria(Location.class, "outer")
            .add(Restrictions.eq("retired", false))
            .add(Subqueries.eq(new Long(tags.size()), numberOfMatchingTags)).list();
}

From source file:org.openmrs.module.emr.reporting.cohort.definition.evaluator.DiagnosisCohortDefinitionEvaluator.java

License:Open Source License

@Override
public EvaluatedCohort evaluate(CohortDefinition cohortDefinition, EvaluationContext context)
        throws EvaluationException {
    DiagnosisMetadata dmd = emrApiProperties.getDiagnosisMetadata();

    DiagnosisCohortDefinition cd = (DiagnosisCohortDefinition) cohortDefinition;

    if (cd.isIncludeAllCodedDiagnoses() && cd.getCodedDiagnoses() != null) {
        throw new IllegalArgumentException(
                "Cannot specify both includeAllCodedDiagnoses, and specific coded diagnoses");
    }/*www.  j  ava  2 s .  com*/

    Criteria crit = sessionFactory.getCurrentSession().createCriteria(Obs.class, "obsgroup");
    crit.setProjection(Projections.distinct(Projections.property("person.id")));

    crit.add(Restrictions.eq("voided", false));
    crit.createCriteria("person").add(Restrictions.eq("voided", false));

    // we're looking for an obs group whose grouping concept is VISIT DIAGNOSES (or the equivalent)
    crit.add(Restrictions.eq("concept", dmd.getDiagnosisSetConcept()));

    if (cd.getOnOrAfter() != null) {
        crit.add(Restrictions.ge("obsDatetime", cd.getOnOrAfter()));
    }
    if (cd.getOnOrBefore() != null) {
        crit.add(Restrictions.le("obsDatetime", DateUtil.getEndOfDayIfTimeExcluded(cd.getOnOrBefore())));
    }

    if (cd.getDiagnosisOrder() != null) {
        DetachedCriteria orderClause = DetachedCriteria.forClass(Obs.class, "orderObs");
        orderClause.add(Restrictions.eq("voided", false));
        orderClause.add(Restrictions.eq("concept", dmd.getDiagnosisOrderConcept()));
        orderClause.add(Restrictions.eq("valueCoded", dmd.getConceptFor(cd.getDiagnosisOrder())));
        orderClause.add(Restrictions.eqProperty("obsGroup", "obsgroup.id"));
        orderClause.setProjection(Projections.property("id"));
        crit.add(Subqueries.exists(orderClause));
    }

    if (cd.getCertainty() != null) {
        DetachedCriteria certaintyClause = DetachedCriteria.forClass(Obs.class, "certaintyObs");
        certaintyClause.add(Restrictions.eq("voided", false));
        certaintyClause.add(Restrictions.eq("concept", dmd.getDiagnosisCertaintyConcept()));
        certaintyClause.add(Restrictions.eq("valueCoded", dmd.getConceptFor(cd.getCertainty())));
        certaintyClause.add(Restrictions.eqProperty("obsGroup", "obsgroup.id"));
        certaintyClause.setProjection(Projections.property("id"));
        crit.add(Subqueries.exists(certaintyClause));
    }

    if (cd.isIncludeAllCodedDiagnoses()) {
        // Note: since every diagnosis is either coded or non-coded if they want to include all coded *and* non-coded
        // diagnoses, we can just ignore both clauses
        if (!cd.isIncludeAllNonCodedDiagnoses()) {
            DetachedCriteria anyCodedClause = DetachedCriteria.forClass(Obs.class, "codedDiagnosisObs");
            anyCodedClause.add(Restrictions.eq("voided", false));
            anyCodedClause.add(Restrictions.eq("concept", dmd.getCodedDiagnosisConcept()));
            anyCodedClause.add(Restrictions.eqProperty("obsGroup", "obsgroup.id"));
            anyCodedClause.setProjection(Projections.property("id"));
            crit.add(Subqueries.exists(anyCodedClause));
        }
    } else if (cd.getCodedDiagnoses() != null || cd.getExcludeCodedDiagnoses() != null) {
        if (cd.isIncludeAllNonCodedDiagnoses()) {
            throw new IllegalArgumentException(
                    "Not Yet Implemented: handling both all-non-coded and specific coded diagnoses together");
        }
        if (!cd.isIncludeAllNonCodedDiagnoses()) {
            DetachedCriteria specificCodedClause = DetachedCriteria.forClass(Obs.class, "codedDiagnosisObs");
            specificCodedClause.add(Restrictions.eq("voided", false));
            specificCodedClause.add(Restrictions.eq("concept", dmd.getCodedDiagnosisConcept()));
            if (cd.getCodedDiagnoses() != null) {
                specificCodedClause.add(Restrictions.in("valueCoded", cd.getCodedDiagnoses()));
            }
            if (cd.getExcludeCodedDiagnoses() != null) {
                specificCodedClause
                        .add(Restrictions.not(Restrictions.in("valueCoded", cd.getExcludeCodedDiagnoses())));
            }
            specificCodedClause.add(Restrictions.eqProperty("obsGroup", "obsgroup.id"));
            specificCodedClause.setProjection(Projections.property("id"));
            crit.add(Subqueries.exists(specificCodedClause));
        }
    } else if (cd.isIncludeAllNonCodedDiagnoses()) {
        DetachedCriteria anyNonCodedClause = DetachedCriteria.forClass(Obs.class, "nonCodedDiagnosisObs");
        anyNonCodedClause.add(Restrictions.eq("voided", false));
        anyNonCodedClause.add(Restrictions.eq("concept", dmd.getNonCodedDiagnosisConcept()));
        anyNonCodedClause.add(Restrictions.eqProperty("obsGroup", "obsgroup.id"));
        anyNonCodedClause.setProjection(Projections.property("id"));
        crit.add(Subqueries.exists(anyNonCodedClause));
    }

    Cohort c = new Cohort();
    for (Integer i : (List<Integer>) crit.list()) {
        c.addMember(i);
    }
    return new EvaluatedCohort(c, cohortDefinition, context);
}

From source file:org.openmrs.module.metadatasharing.api.db.hibernate.HibernateCompatibility1_9.java

License:Open Source License

private void filterConceptWords(Criteria criteria, boolean includeRetired, String filter) {
    criteria.createAlias("concept", "concept");
    if (!includeRetired) {
        criteria.add(Restrictions.eq("concept.retired", includeRetired));
    }/*from w  ww .  j  a va  2 s  .co  m*/

    if (!StringUtils.isEmpty(filter)) {
        Iterator<String> words = ConceptWord.getUniqueWords(filter).iterator();
        if (words.hasNext()) {
            criteria.add(Restrictions.like("word", words.next(), MatchMode.START));
            while (words.hasNext()) {
                DetachedCriteria crit = DetachedCriteria.forClass(ConceptWord.class)
                        .setProjection(Property.forName("concept"))
                        .add(Restrictions.eqProperty("concept", "conceptWord.concept"))
                        .add(Restrictions.like("word", words.next(), MatchMode.START));

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

From source file:org.opennms.dashboard.server.CriteriaAddingVisitor.java

License:Open Source License

/**
 * <p>addCriteriaForCategories</p>
 *
 * @param criteria a {@link org.opennms.netmgt.model.OnmsCriteria} object.
 * @param categories a {@link java.lang.String} object.
 *///from  ww  w .j a  va  2  s  . c o  m
public void addCriteriaForCategories(OnmsCriteria criteria, String... categories) {
    if (criteria.resultsOfType(OnmsMonitoredService.class) || criteria.resultsOfType(OnmsOutage.class)) {
        // Make a detached criteria to subselect the node IDs that are in the
        // specified surveillance categories
        DetachedCriteria categoryNodeCriteria = DetachedCriteria.forClass(OnmsNode.class, "categoryNodes");

        // HACK: Hibernate 3.6 aliases 'categoryNodes' as 'categoryNodes_' so use that for the raw SQL statement.
        // Also note that the database field that we use here is 'nodeId' but the bean property for node ID
        // in OnmsNode is 'id'.
        String sql = "categoryNodes_.nodeId in (select distinct cn.nodeId from category_node cn join categories c on cn.categoryId = c.categoryId where c.categoryName in ("
                + commaDelimitedQuestionMarks(categories.length) + "))";
        categoryNodeCriteria.add(
                Restrictions.sqlRestriction(sql, categories, arrayOfType(categories.length, new StringType())));

        // Join the categoryNodes IDs found by the subselect with the outer 'node' alias.
        // This requires that the criteria already has a 'node' alias to the node table.
        //
        // @see org.opennms.web.svclayer.support.DefaultRtcService#createOutageCriteria()
        // @see org.opennms.web.svclayer.support.DefaultRtcService#createServiceCriteria()
        //
        categoryNodeCriteria.add(Restrictions.eqProperty("categoryNodes.id", "node.id"));

        // Add a projection for 'id' so that the categoryNodes.id can be joined to
        // node.id in the outer criteria
        categoryNodeCriteria.setProjection(Projections.property("id"));

        // Use an exists subquery to evaluate the subselect
        criteria.add(Subqueries.exists(categoryNodeCriteria));
    } else {
        // TODO: This case assumes that the OnmsCriteria is querying an object with a 'nodeId' property.
        // I'm not sure this is ever used... I think this visitor is just for OnmsMonitoredService and 
        // OnmsOutage queries.
        String sql = "{alias}.nodeId in (select distinct cn.nodeId from category_node cn join categories c on cn.categoryId = c.categoryId where c.categoryName in ("
                + commaDelimitedQuestionMarks(categories.length) + "))";
        criteria.add(
                Restrictions.sqlRestriction(sql, categories, arrayOfType(categories.length, new StringType())));
    }
}

From source file:org.opensingular.flow.persistence.service.AbstractHibernatePersistenceService.java

License:Apache License

public List<PROCESS_INSTANCE> retrieveProcessInstancesWith(PROCESS_DEF process, Date dataInicio, Date dataFim,
        java.util.Collection<? extends TASK_DEF> states) {
    Objects.requireNonNull(process);
    final Criteria c = getSession().createCriteria(getClassProcessInstance(), "PI");
    c.createAlias("PI.processVersion", "DEF");
    c.add(Restrictions.eq("DEF.processDefinition", process));
    if (states != null && !states.isEmpty()) {
        DetachedCriteria sub = DetachedCriteria.forClass(getClassTaskInstance(), "T");
        sub.add(Restrictions.eqProperty("T.processInstance.cod", "PI.cod"));
        sub.createAlias("T.task", "TV");
        sub.add(Restrictions.in("TV.taskDefinition", states));
        sub.add(Restrictions.isNull("T.endDate"));
        sub.setProjection(Projections.id());

        c.add(Subqueries.exists(sub));/*from   ww  w .  j av  a2 s  . c o m*/
    }
    if (dataInicio != null && dataFim != null) {
        c.add(Restrictions.or(
                Restrictions.and(Restrictions.ge("PI.beginDate", dataInicio),
                        Restrictions.lt("PI.beginDate", dataFim)),
                Restrictions.and(Restrictions.ge("PI.endDate", dataInicio),
                        Restrictions.lt("PI.endDate", dataFim)),
                Restrictions.and(Restrictions.lt("PI.beginDate", dataInicio),
                        Restrictions.ge("PI.endDate", dataInicio)),
                Restrictions.and(Restrictions.isNull("PI.endDate"), Restrictions.lt("PI.beginDate", dataFim))));
    } else if (dataInicio != null) {
        c.add(Restrictions.or(Restrictions.ge("PI.beginDate", dataInicio),
                Restrictions.ge("PI.endDate", dataInicio), Restrictions
                        .and(Restrictions.lt("PI.beginDate", dataInicio), Restrictions.isNull("PI.endDate"))));
    } else if (dataFim != null) {
        c.add(Restrictions.or(Restrictions.le("PI.beginDate", dataFim),
                Restrictions.le("PI.endDate", dataFim)));
    }
    c.addOrder(Order.desc("PI.beginDate"));
    return c.list();
}

From source file:org.opensingular.flow.persistence.service.AbstractHibernatePersistenceService.java

License:Apache License

public List<PROCESS_INSTANCE> retrieveProcessInstancesWith(PROCESS_DEF process, SUser creatingUser,
        Boolean active) {/*from   ww w  . ja v a 2 s  .c om*/
    Objects.requireNonNull(process);
    Criteria c = getSession().createCriteria(getClassProcessInstance(), "PI");
    c.createAlias("PI.processVersion", "DEF");
    c.add(Restrictions.eq("DEF.processDefinition", process));

    if (active != null) {
        DetachedCriteria sub = DetachedCriteria.forClass(getClassTaskInstance(), "T");
        sub.createAlias("T.task", "TA");
        sub.add(Restrictions.eqProperty("T.processInstance.cod", "PI.cod"));
        sub.add(Restrictions.isNull("T.endDate"));
        if (active) {
            sub.add(Restrictions.ne("TA.type", TaskType.END));
        } else {
            sub.add(Restrictions.eq("TA.type", TaskType.END));
        }
        sub.setProjection(Projections.id());

        c.add(Subqueries.exists(sub));
    }

    if (creatingUser != null) {
        c.add(Restrictions.eq("PI.userCreator", creatingUser));
    }
    c.setCacheable(true).setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
    return c.list();
}

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

License:Apache License

private Criterion makeCriterion(ConditionalCriteria crit) {
    if (crit == null) {
        return null;
    }/*from  ww  w.  j  av  a2 s .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)) {
        // Hibernate bug HHH-5339 + PostgreSQL missing 'number like string' conversion
        return new NumericLikeExpression(makePathWithAlias(crit.getPropertyFullName()),
                crit.getFirstOperant().toString(), false);
    } else if (Operator.IgnoreCaseLike.equals(operator)) {
        // Hibernate bug HHH-5339 + PostgreSQL missing 'number like string' conversion
        return new NumericLikeExpression(makePathWithAlias(crit.getPropertyFullName()),
                crit.getFirstOperant().toString(), true);
    } 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.ltProperty(makePathWithAlias(crit.getPropertyFullName()),
                (String) crit.getFirstOperant());
    } else if (Operator.LessThanOrEqualProperty.equals(operator)) {
        return Restrictions.leProperty(makePathWithAlias(crit.getPropertyFullName()),
                (String) crit.getFirstOperant());
    } else if (Operator.GreatThanProperty.equals(operator)) {
        return Restrictions.gtProperty(makePathWithAlias(crit.getPropertyFullName()),
                (String) crit.getFirstOperant());
    } else if (Operator.GreatThanOrEqualProperty.equals(operator)) {
        return Restrictions.geProperty(makePathWithAlias(crit.getPropertyFullName()),
                (String) crit.getFirstOperant());
    } else {
        return null;
    }
}

From source file:to.etc.domui.hibernate.model.CriteriaCreatingVisitor.java

License:Open Source License

/**
 * Child-related subquery: determine existence of children having certain characteristics. Because
 * the worthless Hibernate "meta model" API and the utterly disgusting way that mapping data is
 * "stored" in Hibernate we resort to getting the generic type of the child property's collection
 * to determine the type where the subquery is executed on.
 * @see to.etc.webapp.query.QNodeVisitorBase#visitExistsSubquery(to.etc.webapp.query.QExistsSubquery)
 *///from   w w w.  j av  a  2s.  c om
@Override
public void visitExistsSubquery(QExistsSubquery<?> q) throws Exception {
    String parentAlias = getCurrentAlias();
    Class<?> parentBaseClass = q.getParentQuery().getBaseClass();
    PropertyMetaModel<?> pmm = MetaManager.getPropertyMeta(parentBaseClass, q.getParentProperty());

    //-- If we have a dotted name it can only be parent.parent.parent.childList like (with multiple parents). Parse all parents.
    String childListProperty = q.getParentProperty();
    int ldot = childListProperty.lastIndexOf('.');
    if (ldot != -1) {
        //-- Join all parents, and get the last parent's reference and name
        String last = parseSubcriteria(childListProperty, true); // Create the join path;
        String parentpath = childListProperty.substring(0, ldot); // This now holds parent.parent.parent
        childListProperty = childListProperty.substring(ldot + 1); // And this childList

        //-- We need a "new" parent class: the class that actually contains the "child" list...
        PropertyMetaModel<?> parentpm = MetaManager.getPropertyMeta(parentBaseClass, parentpath);
        parentBaseClass = parentpm.getActualType();

        //-- The above join will have created another alias to the joined table; this is the first part of the "last" reference (which is alias.property).
        ldot = last.indexOf('.');
        if (ldot < 0)
            throw new IllegalStateException("Invalid result from parseSubcriteria inside exists.");
        parentAlias = last.substring(0, ldot);
    }

    //-- Should be List type
    if (!List.class.isAssignableFrom(pmm.getActualType()))
        throw new ProgrammerErrorException("The property '" + q.getParentQuery().getBaseClass() + "."
                + q.getParentProperty() + "' should be a list (it is a " + pmm.getActualType() + ")");

    //-- Make sure there is a where condition to restrict
    QOperatorNode where = q.getRestrictions();
    //      if(where == null)
    //         throw new ProgrammerErrorException("exists subquery has no restrictions: " + this);

    //-- Get the list's generic compound type because we're unable to get it from Hibernate easily.
    Class<?> coltype = MetaManager.findCollectionType(pmm.getGenericActualType());
    if (coltype == null)
        throw new ProgrammerErrorException("The property '" + q.getParentQuery().getBaseClass() + "."
                + q.getParentProperty() + "' has an undeterminable child type");

    //-- 2. Create an exists subquery; create a sub-statement
    DetachedCriteria dc = DetachedCriteria.forClass(coltype, nextAlias());
    Criterion exists = Subqueries.exists(dc);
    dc.setProjection(Projections.id()); // Whatever: just some thingy.

    //-- Append the join condition; we need all children here that are in the parent's collection. We need the parent reference to use in the child.
    ClassMetadata childmd = m_session.getSessionFactory().getClassMetadata(coltype);

    //-- Entering the crofty hellhole that is Hibernate meta"data" 8-(

    ClassMetadata parentmd = m_session.getSessionFactory().getClassMetadata(parentBaseClass);
    int index = findMoronicPropertyIndexBecauseHibernateIsTooStupidToHaveAPropertyMetaDamnit(parentmd,
            childListProperty);
    if (index == -1)
        throw new IllegalStateException(
                "Hibernate does not know property '" + childListProperty + " in " + parentmd.getEntityName());
    Type type = parentmd.getPropertyTypes()[index];
    CollectionType bt = (CollectionType) type;
    final OneToManyPersister persister = (OneToManyPersister) ((SessionFactoryImpl) m_session
            .getSessionFactory()).getCollectionPersister(bt.getRole());
    String[] keyCols = persister.getKeyColumnNames();

    //-- Try to locate those FK column names in the FK table so we can fucking locate the mapping property.
    String childupprop = findCruddyChildProperty(childmd, keyCols);
    if (childupprop == null)
        throw new IllegalStateException("Cannot find child's parent property in crufty Hibernate metadata: "
                + Arrays.toString(keyCols));

    //-- Well, that was it. What a sheitfest. Add the join condition to the parent
    dc.add(Restrictions.eqProperty(childupprop + "." + childmd.getIdentifierPropertyName(),
            parentAlias + "." + parentmd.getIdentifierPropertyName()));

    //-- Sigh; Recursively apply all parts to the detached thingerydoo
    Object old = m_currentCriteria;
    Class<?> oldroot = m_rootClass;
    Map<String, String> oldAliases = m_aliasMap;
    m_aliasMap = new HashMap<String, String>();

    m_rootClass = q.getBaseClass();
    checkHibernateClass(m_rootClass);
    m_currentCriteria = dc;
    if (where != null)
        where.visit(this);
    if (m_last != null) {
        dc.add(m_last);
        m_last = null;
    }
    m_aliasMap = oldAliases;
    m_currentCriteria = old;
    m_rootClass = oldroot;
    m_last = exists;
}