Example usage for org.hibernate.criterion Projections distinct

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

Introduction

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

Prototype

public static Projection distinct(Projection projection) 

Source Link

Document

Create a distinct projection from a projection.

Usage

From source file:au.org.theark.core.dao.StudyDao.java

License:Open Source License

private Criteria buildGeneralSubjectCriteria(SubjectVO subjectVO) {
    Criteria criteria = getSession().createCriteria(LinkSubjectStudy.class);
    criteria.createAlias("person", "p");
    if (subjectVO.getLinkSubjectStudy().getStudy() != null) {
        criteria.add(Restrictions.eq("study.id", subjectVO.getLinkSubjectStudy().getStudy().getId()));
    } else {/*ww w  .ja  v a 2s .  c o m*/
        criteria.add(Restrictions.in("study", subjectVO.getStudyList()));
        criteria.createAlias("study", "st");
        criteria.addOrder(Order.asc("st.name"));
    }
    if (subjectVO.getLinkSubjectStudy().getPerson() != null) {

        if (subjectVO.getLinkSubjectStudy().getPerson().getId() != null) {
            criteria.add(Restrictions.eq("p.id", subjectVO.getLinkSubjectStudy().getPerson().getId()));
        }

        if (subjectVO.getLinkSubjectStudy().getPerson().getFirstName() != null) {
            criteria.add(Restrictions.ilike("p.firstName",
                    subjectVO.getLinkSubjectStudy().getPerson().getFirstName(), MatchMode.ANYWHERE));
        }

        if (subjectVO.getLinkSubjectStudy().getPerson().getMiddleName() != null) {
            criteria.add(Restrictions.ilike("p.middleName",
                    subjectVO.getLinkSubjectStudy().getPerson().getMiddleName(), MatchMode.ANYWHERE));
        }

        if (subjectVO.getLinkSubjectStudy().getPerson().getLastName() != null) {
            /* old code pre George adding personlastname lookup criteria.add(Restrictions.ilike("p.lastName", subjectVO.getLinkSubjectStudy().getPerson().getLastName(), MatchMode.ANYWHERE));*/
            //log.info("Lastname: " + subjectVO.getLinkSubjectStudy().getPerson().getLastName());
            DetachedCriteria previousLastNames = DetachedCriteria.forClass(PersonLastnameHistory.class, "l")
                    .setProjection(Projections.property("l.lastName"))
                    .add(Restrictions.ilike("l.lastName",
                            subjectVO.getLinkSubjectStudy().getPerson().getLastName(), MatchMode.ANYWHERE))
                    .add(Restrictions.eqProperty("p.id", "l.person.id"));
            criteria.add(Restrictions.or(Restrictions.ilike("p.lastName",
                    subjectVO.getLinkSubjectStudy().getPerson().getLastName(), MatchMode.ANYWHERE),
                    Subqueries.exists(previousLastNames)));
        }

        if (subjectVO.getLinkSubjectStudy().getPerson().getDateOfBirth() != null) {
            criteria.add(Restrictions.eq("p.dateOfBirth",
                    subjectVO.getLinkSubjectStudy().getPerson().getDateOfBirth()));
        }

        if (subjectVO.getLinkSubjectStudy().getPerson().getGenderType() != null) {
            criteria.add(Restrictions.eq("p.genderType.id",
                    subjectVO.getLinkSubjectStudy().getPerson().getGenderType().getId()));
        }

        if (subjectVO.getLinkSubjectStudy().getPerson().getVitalStatus() != null) {
            criteria.add(Restrictions.eq("p.vitalStatus.id",
                    subjectVO.getLinkSubjectStudy().getPerson().getVitalStatus().getId()));
        }

        if (!subjectVO.getLinkSubjectStudy().getPerson().getOtherIDs().isEmpty()) {
            OtherID o = (OtherID) subjectVO.getLinkSubjectStudy().getPerson().getOtherIDs().toArray()[0];
            if (o != null && o.getOtherID() != null && !o.getOtherID().isEmpty()) {
                log.info("OtherID search");
                //               DetachedCriteria otherID = DetachedCriteria.forClass(OtherID.class, "O")
                //                     .setProjection(Projections.projectionList().add(Projections.property("O.otherID")))
                //                     .add(Restrictions.ilike("O.otherID", ((OtherID) subjectVO.getLinkSubjectStudy().getPerson().getOtherIDs().toArray()[0]).getOtherID(), MatchMode.EXACT))
                //                     .add(Restrictions.eqProperty("p.id", "O.person.id"));
                //               criteria.add(Subqueries.exists(otherID));
                criteria.createAlias("p.otherIDs", "o");
                criteria.add(Restrictions.ilike("o.otherID",
                        ((OtherID) subjectVO.getLinkSubjectStudy().getPerson().getOtherIDs().toArray()[0])
                                .getOtherID(),
                        MatchMode.ANYWHERE));
                criteria.setProjection(Projections.distinct(
                        Projections.projectionList().add(Projections.property("o.personid"), "lss.person.id")));
            }
        }
    }

    if (subjectVO.getLinkSubjectStudy().getSubjectUID() != null
            && subjectVO.getLinkSubjectStudy().getSubjectUID().length() > 0) {
        criteria.add(Restrictions.ilike("subjectUID", subjectVO.getLinkSubjectStudy().getSubjectUID(),
                MatchMode.ANYWHERE));
    }

    if (subjectVO.getLinkSubjectStudy().getSubjectStatus() != null) {
        criteria.add(Restrictions.eq("subjectStatus", subjectVO.getLinkSubjectStudy().getSubjectStatus()));
        SubjectStatus subjectStatus = getSubjectStatus("Archive");
        if (subjectStatus != null) {
            criteria.add(Restrictions.ne("subjectStatus", subjectStatus));
        }
    } else {
        SubjectStatus subjectStatus = getSubjectStatus("Archive");
        if (subjectStatus != null) {
            criteria.add(Restrictions.ne("subjectStatus", subjectStatus));
        }
    }
    if (subjectVO.getRelativeUIDs().size() > 0) {
        criteria.add(Restrictions.not(Restrictions.in("subjectUID", subjectVO.getRelativeUIDs().toArray())));
    }

    criteria.setProjection(Projections.distinct(Projections.projectionList().add(Projections.id())));

    criteria.addOrder(Order.asc("subjectUID"));
    return criteria;
}

From source file:au.org.theark.core.dao.StudyDao.java

License:Open Source License

public List<Study> getStudiesForUser(ArkUser arkUser, Study study) {

    Criteria criteria = getSession().createCriteria(ArkUserRole.class);
    criteria.createAlias("arkStudy", "arkStudy");

    criteria.add(Restrictions.eq("arkUser", arkUser));// Represents the user
    // either who is
    // logged in or one
    // that is provided
    if (study.getId() != null) {
        criteria.add(Restrictions.eq("arkStudy.id", study.getId()));
    }//from  w ww.j  a v a2 s .c  o m

    if (study.getName() != null) {
        criteria.add(Restrictions.ilike("arkStudy.name", study.getName(), MatchMode.ANYWHERE));
    }
    criteria.setProjection(Projections.distinct(Projections.property("study")));
    List<Study> studies = (List<Study>) criteria.list();
    return studies;

}

From source file:au.org.theark.core.dao.StudyDao.java

License:Open Source License

private List<Long> applyConsentStatusFilters(DataExtractionVO allTheData, Search search,
        List<Long> idsToInclude) {

    //for(Long l : idsToInclude) {
    //   log.info("including: " + l);
    //}/*  w  w w .j  a v a 2  s.  c om*/
    boolean hasConsentFilters = false;
    if (search.getQueryFilters().isEmpty()) {
        return idsToInclude;
    } else {
        for (QueryFilter filter : search.getQueryFilters()) {
            if (filter.getConsentStatusField() != null) {
                hasConsentFilters = true;
            }
        }
    }
    Criteria filter = getSession().createCriteria(Consent.class, "c");
    filter.add(Restrictions.eq("c.study.id", search.getStudy().getId()));
    filter.createAlias("c.linkSubjectStudy", "lss");
    if (!idsToInclude.isEmpty()) {
        filter.add(Restrictions.in("lss.id", idsToInclude));
    }
    filter.createAlias("c.studyComponentStatus", "cscs");
    filter.createAlias("c.studyComp", "csc");

    if (!hasConsentFilters) {

        for (QueryFilter qf : search.getQueryFilters()) {
            if (qf.getConsentStatusField() != null) {
                switch (qf.getOperator()) {
                case EQUAL:
                    filter.add(Restrictions.eq(getConsentFilterFieldName(qf), qf.getValue()));
                    break;
                case BETWEEN:
                    filter.add(Restrictions.between(getConsentFilterFieldName(qf), qf.getValue(),
                            qf.getSecondValue()));
                    break;
                case GREATER_THAN:
                    filter.add(Restrictions.gt(getConsentFilterFieldName(qf), qf.getValue()));
                    break;
                case GREATER_THAN_OR_EQUAL:
                    filter.add(Restrictions.ge(getConsentFilterFieldName(qf), qf.getValue()));
                    break;
                case IS_EMPTY:
                    filter.add(Restrictions.isEmpty(getConsentFilterFieldName(qf)));
                    break;
                case IS_NOT_EMPTY:
                    filter.add(Restrictions.isNotEmpty(getConsentFilterFieldName(qf)));
                    break;
                case LESS_THAN:
                    filter.add(Restrictions.lt(getConsentFilterFieldName(qf), qf.getValue()));
                    break;
                case LESS_THAN_OR_EQUAL:
                    filter.add(Restrictions.le(getConsentFilterFieldName(qf), qf.getValue()));
                    break;
                case LIKE:
                    filter.add(Restrictions.like(getConsentFilterFieldName(qf), qf.getValue(),
                            MatchMode.ANYWHERE));
                    break;
                case NOT_EQUAL:
                    filter.add(Restrictions.ne(getConsentFilterFieldName(qf), qf.getValue()));
                    break;
                default:
                    break;
                }
            }
        }
    }
    filter.setProjection(
            Projections.distinct(Projections.projectionList().add(Projections.property("lss.id"))));

    List<Long> consentStatusIDs = filter.list();

    Collection<Consent> csData = Collections.EMPTY_LIST;

    if (!consentStatusIDs.isEmpty()) {
        Criteria consentData = getSession().createCriteria(Consent.class, "c");
        consentData.add(Restrictions.eq("c.study.id", search.getStudy().getId()));
        consentData.createAlias("c.linkSubjectStudy", "lss");
        consentData.add(Restrictions.in("lss.id", consentStatusIDs));
        csData = consentData.list();
    }

    HashMap<String, ExtractionVO> hashOfConsentStatusData = allTheData.getConsentStatusData();

    ExtractionVO valuesForThisLss = new ExtractionVO();
    HashMap<String, String> map = null;
    LinkSubjectStudy previousLss = null;
    int count = 0;
    //will try to order our results and can therefore just compare to last LSS and either add to or create new Extraction VO
    for (Consent data : csData) {
        if (previousLss == null) {
            map = new HashMap<String, String>();
            previousLss = data.getLinkSubjectStudy();
            count = 0;
        } else if (data.getLinkSubjectStudy().getId().equals(previousLss.getId())) {
            //then just put the data in
            count++;
        } else { //if its a new LSS finalize previous map, etc
            valuesForThisLss.setKeyValues(map);
            valuesForThisLss.setSubjectUid(previousLss.getSubjectUID());
            hashOfConsentStatusData.put(previousLss.getSubjectUID(), valuesForThisLss);
            previousLss = data.getLinkSubjectStudy();
            map = new HashMap<String, String>();//reset
            valuesForThisLss = new ExtractionVO();
            count = 0;
        }
        if (data.getStudyComp().getName() != null) {
            map.put(count + "_Study Component Name", data.getStudyComp().getName());
        }
        if (data.getStudyComponentStatus() != null) {
            map.put(count + "_Study Component Status", data.getStudyComponentStatus().getName());
        }
        if (data.getConsentDate() != null) {
            map.put(count + "_Consent Date", data.getConsentDate().toString());
        }
        if (data.getConsentedBy() != null) {
            map.put(count + "_Consented By", data.getConsentedBy());
        }
    }

    //finalize the last entered key value sets/extraction VOs
    if (map != null && previousLss != null) {
        valuesForThisLss.setKeyValues(map);
        valuesForThisLss.setSubjectUid(previousLss.getSubjectUID());
        hashOfConsentStatusData.put(previousLss.getSubjectUID(), valuesForThisLss);
    }

    //can probably now go ahead and add these to the dataVO...even though inevitable further filters may further axe this list or parts of it.
    allTheData.setConsentStatusData(hashOfConsentStatusData);
    if (hasConsentFilters) {
        return consentStatusIDs;
    } else {
        return idsToInclude;
    }
}

From source file:br.al.contractmanager.dao.UsuarioDao.java

@Transactional(readOnly = true)
public int count() {
    Session session = sessionFactory.getCurrentSession();
    try {/*  w  w  w . j a v  a2  s . c o  m*/
        Criteria criteria = session.createCriteria(Usuario.class);
        criteria.setProjection(Projections.distinct(Projections.id()));
        return ((Long) criteria.setProjection(Projections.rowCount()).uniqueResult()).intValue();
    } catch (HibernateException e) {
        System.out.println(e.getMessage());
        return 0;
    }
}

From source file:br.al.contractmanager.dao.UsuarioDao.java

@Transactional(readOnly = true)
public int count(String termo) {
    Session session = sessionFactory.getCurrentSession();
    try {/*from ww w .j  av a 2s. c  o m*/
        Criteria criteria = session.createCriteria(Usuario.class);
        criteria.add(Restrictions.or(Restrictions.eq("matricula", termo),
                Restrictions.like("nomeUsuario", termo, MatchMode.ANYWHERE).ignoreCase(),
                Restrictions.like("nomeCompleto", termo, MatchMode.ANYWHERE).ignoreCase()))
                .setProjection(Projections.distinct(Projections.id()));
        return ((Long) criteria.setProjection(Projections.rowCount()).uniqueResult()).intValue();
    } catch (HibernateException e) {
        System.out.println(e.getMessage());
        return 0;
    }
}

From source file:br.com.muranodesign.dao.impl.ChamadaDAOImpl.java

License:Creative Commons License

@SuppressWarnings("unchecked")
public List<Compensacao> compensacaoAluno(int idAluno) {
    Criteria criteria = getSession().createCriteria(Chamada.class);
    criteria.createAlias("aluno", "aluno");
    criteria.add(Restrictions.eq("aluno.idAluno", idAluno));
    criteria.add(Restrictions.isNotNull("compensacao"));
    criteria.setProjection(Projections.distinct(Projections.property("compensacao")));
    return criteria.list();
}

From source file:br.com.sgejs.dao.DaoArquivo.java

public List getAnos() throws HibernateException {
    Criteria cri = sessao.createCriteria(classe);
    cri.setProjection(Projections.distinct(Projections.property("ano")));
    cri.addOrder(Order.asc("ano"));
    return cri.list();
}

From source file:br.com.sgejs.dao.DaoArquivo.java

public List getCursosDoAno(int ano) throws HibernateException {
    Criteria cri = sessao.createCriteria(classe);
    cri.add(Restrictions.eq("ano", ano));
    cri.setProjection(Projections.distinct(Projections.property("curso")));
    return cri.list();
}

From source file:br.com.sgejs.dao.DaoArquivo.java

public List getTipoDeArquivoDoAno(int ano, Curso curso) throws HibernateException {
    Criteria cri = sessao.createCriteria(classe);
    cri.add(Restrictions.eq("ano", ano)).add(Restrictions.eq("curso", curso));
    cri.setProjection(Projections.distinct(Projections.property("tipo")));
    return cri.list();
}

From source file:br.com.tcc.service.persistence.PaginationHelper.java

/**
 * <p>// w  w  w  . j a v a 2  s  .c  o  m
 * <b>ATENO:</b> Este mtodo <b>altera permanentemente</b> o objeto {@link Criteria} recebido como parmetro. Qualquer {@link Projection} ou {@link ResultTransformer} configurado no criteria
 * <b>ser substitudo</b>.
 * </p>
 * <p>
 * Use o parmetro <code>distinct</code> para definir se o {@link ResultTransformer} deve ser
 * {@link Criteria.DISTINCT_ROOT_ENTITY} ou apenas {@link Criteria.ROOT_ENTITY}
 * e se deve ser usado <code>distinct count(*)</code> ou apenas <code>count(*)</code>.
 * </p>
 * @param criteria O Criteria a ser utilizado
 * @param pagination O objeto com a paginao desejada.
 * @param distinct Se a consulta deve usar <code>SQL DISTINCT</code>.
 * @return Um novo objeto de paginao referente  consulta atual.
 */
private static Pagination getTotalItemsForCriteria(Criteria criteria, Pagination pagination, boolean distinct) {

    Projection count = Projections.rowCount();
    if (distinct) {
        count = Projections.distinct(count);
    }
    int totalItems = (Integer) criteria.setProjection(count).uniqueResult();
    criteria.setProjection(null)
            .setResultTransformer(distinct ? Criteria.DISTINCT_ROOT_ENTITY : Criteria.ROOT_ENTITY);
    return new Pagination(pagination.getPageSize(), pagination.getCurrentPage(), totalItems,
            pagination.getOrdering());

}