Example usage for org.hibernate.criterion Projections id

List of usage examples for org.hibernate.criterion Projections id

Introduction

In this page you can find the example usage for org.hibernate.criterion Projections id.

Prototype

public static IdentifierProjection id() 

Source Link

Document

An identifier value projection.

Usage

From source file:org.mzd.shap.domain.dao.FeatureDaoSpringHibernate.java

License:Open Source License

public Feature findBySequenceAndLocus(final Sequence sequence, String locusTag, final boolean minimal)
        throws FeatureException {

    Pattern p = Pattern.compile("^\\D+(\\d+)$");
    Matcher m = p.matcher(locusTag);
    if (!m.matches()) {
        throw new FeatureException("LocusTag [" + locusTag + "] does not conform to pattern [\\D+\\d+]");
    }/*from www .  ja va  2 s  .c  o m*/

    final Integer rank = Integer.parseInt(m.group(1)) - 1;

    return getHibernateTemplate().execute(new HibernateCallback<Feature>() {
        public Feature doInHibernate(Session session) throws HibernateException, SQLException {
            Criteria crit = session.createCriteria(getPersistentClass())
                    .add(Restrictions.eq("sequence", sequence)).add(Restrictions.eq("rank", rank));

            if (minimal) {
                crit.setProjection(Projections.projectionList().add(Projections.id(), "id")
                        .add(Projections.property("version"), "version"))
                        .setResultTransformer(Transformers.aliasToBean(getPersistentClass()));

            }

            return (Feature) crit.uniqueResult();
        }
    });
}

From source file:org.mzd.shap.domain.dao.SequenceDaoSpringHibernate.java

License:Open Source License

public List<Sequence> minimalFindAll() {
    return getHibernateTemplate().execute(new HibernateCallback<List<Sequence>>() {
        @SuppressWarnings("unchecked")
        public List<Sequence> doInHibernate(Session session) throws HibernateException, SQLException {
            return session.createCriteria(getPersistentClass()).setProjection(Projections.id())
                    .setResultTransformer(Transformers.aliasToBean(getPersistentClass())).list();
        }/*  ww  w. ja  v a2  s .com*/
    });
}

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 va  2  s .  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.openehealth.ipf.commons.flow.repository.FlowRepositoryImpl.java

License:Apache License

private Object execute(FlowFinderCriteria flowFinderCriteria, DetachedCriteria flowStatusCriteria,
        Session session, boolean idProjection) {

    Criteria criteria = flowStatusCriteria.getExecutableCriteria(session);

    if (idProjection) {
        criteria.setProjection(Projections.id());
    }//from  w ww.j a  v a  2 s.c o  m

    int maxResults = flowFinderCriteria.getMaxResults();
    if (maxResults != FlowFinderCriteria.DEFAULT_MAX_RESULTS) {
        criteria.setMaxResults(maxResults);
    }

    if (flowFinderCriteria.hasMessageQuery()) {
        FlowSearchCriteria flowSearchCriteria = new FlowSearchCriteria();
        flowSearchCriteria.setHibernateCriteria(criteria);
        flowSearchCriteria.setInboundMessageQuery(flowFinderCriteria.getInboundMessageQuery());
        flowSearchCriteria.setOutboundMessageQuery(flowFinderCriteria.getOutboundMessageQuery());
        return flowSearchCallback.findFlows(session, flowSearchCriteria);
    } else {
        return criteria.list();
    }
}

From source file:org.openhealthtools.openatna.audit.persistence.dao.hibernate.AbstractHibernateDao.java

License:Apache License

protected List<? extends E> all(int offset, int amount) {
    Criteria messageCriteria = criteria();
    Criteria idCriteria = criteria().setProjection(Projections.id())
            .setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY).addOrder(Order.asc("id"))
            .setFirstResult(offset).setMaxResults(amount);
    List<Long> ids = idCriteria.list();
    if (ids == null || ids.size() == 0) {
        return new ArrayList<E>();
    }/*from  w ww . java  2  s  .  co m*/
    if (ids.size() == 1) {
        messageCriteria.add(Restrictions.eq("id", ids.get(0)));
    } else {
        messageCriteria.add(Restrictions.in("id", ids));
    }
    return list(messageCriteria);
}

From source file:org.openhealthtools.openatna.audit.persistence.dao.hibernate.HibernateQueryBuilder.java

License:Apache License

/**
 * NOTE: HAVE TO USE TWO QUERIES HERE. There is NO way around that I can see to ensure getting
 * back both distinct, and correct max results restrictions.
 *
 * @param query/*from  w  w  w.  j a  v  a  2 s.  c o  m*/
 * @return
 */
public Criteria build(Query query) {

    Map<Query.Target, Set<Query.ConditionalStatement>> map = query.getConditionals();

    CriteriaNode root = new CriteriaNode(idCriteria, "MESSAGE");
    idCriteria.setProjection(Projections.id());
    Set<Query.Target> targets = map.keySet();
    for (Query.Target target : targets) {
        Query.TargetPath tp = Query.createPath(target);
        CriteriaNode node = getNode(root, tp);
        Set<Query.ConditionalStatement> values = map.get(target);
        for (Query.ConditionalStatement value : values) {
            createConditional(root, node, value, tp.getTarget());
        }
    }
    idCriteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
    idCriteria.addOrder(Order.asc("id"));
    List<Long> ids = idCriteria.list();
    if (ids == null || ids.size() == 0) {
        return null;
    }
    if (ids.size() == 1) {
        messageCriteria.add(Restrictions.eq("id", ids.get(0)));
    } else {
        messageCriteria.add(Restrictions.in("id", ids));
    }
    return messageCriteria;
}

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

License:Mozilla Public License

/**
 * Adds attribute value criteria to the given criteria query
 * /*from w  ww  .jav a  2  s .  c  o m*/
 * @param criteria the criteria
 * @param serializedAttributeValues the serialized attribute values
 * @param <AT> the attribute type
 */
public static <AT extends AttributeType> void addAttributeCriteria(Criteria criteria,
        Map<AT, String> serializedAttributeValues) {
    Conjunction conjunction = Restrictions.conjunction();
    int a = 0;

    for (Map.Entry<AT, String> entry : serializedAttributeValues.entrySet()) {
        String alias = "attributes" + (a++);
        DetachedCriteria detachedCriteria = DetachedCriteria.forClass(Location.class)
                .setProjection(Projections.id());
        detachedCriteria.createAlias("attributes", alias);
        detachedCriteria.add(Restrictions.eq(alias + ".attributeType", entry.getKey()));
        detachedCriteria.add(Restrictions.eq(alias + ".valueReference", entry.getValue()));
        detachedCriteria.add(Restrictions.eq(alias + ".voided", false));

        conjunction.add(Property.forName("id").in(detachedCriteria));
    }

    criteria.add(conjunction);
}

From source file:org.openmrs.module.reporting.query.encounter.evaluator.BasicEncounterQueryEvaluator.java

License:Open Source License

@Override
public EncounterQueryResult evaluate(EncounterQuery definition, EvaluationContext context)
        throws EvaluationException {
    context = ObjectUtil.nvl(context, new EvaluationContext());

    BasicEncounterQuery query = (BasicEncounterQuery) definition;
    EncounterQueryResult result = new EncounterQueryResult(query, context);

    Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Encounter.class);
    criteria.setProjection(Projections.id());
    criteria.add(Restrictions.eq("voided", false));

    if (query.getEncounterTypes() != null) {
        criteria.add(Restrictions.in("encounterType", query.getEncounterTypes()));
    }/*from  ww  w.  ja  v  a2s .c o  m*/
    if (query.getOnOrAfter() != null) {
        criteria.add(Restrictions.ge("encounterDatetime", query.getOnOrAfter()));
    }
    if (query.getOnOrBefore() != null) {
        criteria.add(Restrictions.le("encounterDatetime",
                DateUtil.getEndOfDayIfTimeExcluded(query.getOnOrBefore())));
    }

    if (context.getBaseCohort() != null) {
        if (context.getBaseCohort().size() == 0) {
            return result;
        } else {
            criteria.add(Restrictions.in("patient.id", context.getBaseCohort().getMemberIds()));
        }
    }
    if (context instanceof EncounterEvaluationContext) {
        EncounterIdSet baseEncounters = ((EncounterEvaluationContext) context).getBaseEncounters();
        if (baseEncounters != null) {
            if (baseEncounters.getSize() == 0) {
                return result;
            } else {
                criteria.add(Restrictions.in("id", baseEncounters.getMemberIds()));
            }
        }
    }

    for (Integer encounterId : ((List<Integer>) criteria.list())) {
        result.add(encounterId);
    }
    return result;
}

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 w ww .ja  va  2s .  c om*/
    }
    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   w ww . jav a2s .com*/
    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();
}