Example usage for org.hibernate.criterion Projections rowCount

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

Introduction

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

Prototype

public static Projection rowCount() 

Source Link

Document

The query row count, ie.

Usage

From source file:ca.qc.cegepoutaouais.tge.pige.server.ManagementServiceImpl.java

License:Open Source License

@Override
public PagingLoadResult<Loan> getLoans(PagingLoadConfig configs) throws PigeException {

    PermissionHelper.checkLoanManagementPermission(getThreadLocalRequest());

    logger.debug("Rcupration des emprunts " + "[Pagination: dpart=" + configs.getOffset() + ", max="
            + configs.getLimit() + "] ...");

    Transaction tx = null;/* w  ww. j  a  va  2 s . c o  m*/
    List<Loan> loans = null;
    Session session = null;
    Integer loanCount = 0;
    Integer offset = 0;
    Integer limit = 0;

    try {
        session = PigeHibernateUtil.openSession();
        tx = session.beginTransaction();

        Date startDate = null;
        Date endDate = null;

        Criteria loansCriteria = session.createCriteria(Loan.class);
        Criteria usersCriteria = null;

        List<FilterConfig> searchConfigs = configs.get(PIGE.SEARCH_CONFIGS);
        List<FilterConfig> filterConfigs = configs.get(PIGE.FILTER_CONFIGS);

        List<FilterConfig> userParam = null;
        List<FilterConfig> loanParam = null;

        if (searchConfigs != null) {
            for (FilterConfig fc : searchConfigs) {
                if (fc.getField().equals("params")) {
                    logger.debug("Extraction du FilterConfig 'params'...");
                    BaseListFilterConfig blfc = (BaseListFilterConfig) fc;
                    userParam = blfc.get(PIGE.USER_CONFIGS);
                    logger.debug("Extraction de la liste 'user-param'..." + (userParam == null ? "N/D" : "OK"));
                    loanParam = blfc.get(PIGE.LOAN_CONFIGS);
                    logger.debug("Extraction de la liste 'loan-param'..." + (loanParam == null ? "N/D" : "OK"));
                    break;
                }
            }
        }

        Criterion filterCriterion = null;
        Iterator<FilterConfig> itr = null;
        FilterConfig fc = null;

        if (loanParam != null) {
            itr = loanParam.iterator();
            while (itr.hasNext()) {
                fc = itr.next();
                if (fc instanceof BaseDateFilterConfig) {
                    BaseDateFilterConfig dateFC = (BaseDateFilterConfig) fc;
                    startDate = dateFC.get(PIGE.START_DATE, null);
                    endDate = dateFC.get(PIGE.END_DATE, null);
                    itr.remove();
                    break;
                }
            }

            FilterConfig matchModeConfig = new BaseBooleanFilterConfig();
            matchModeConfig.setField(PIGE.MATCH_MODE);
            matchModeConfig.setValue(Boolean.FALSE);
            loanParam.add(matchModeConfig);
            filterCriterion = PigeHibernateUtil.buildFilterCriterion(loanParam);
            if (filterCriterion != null) {
                loansCriteria.add(filterCriterion);
            }

            if (startDate != null) {
                logger.debug("Restrictions sur la date d'chance: entre " + startDate.toString() + " et "
                        + (endDate == null ? new Date() : endDate) + " inclusivement...");
                loansCriteria.add(Restrictions.between(Loan.START_DATE_REF, startDate,
                        (endDate == null ? new Date() : endDate)));
            } else if (endDate != null) {
                logger.debug("Restrictions sur la date d'chance: <= " + endDate.toString());
                loansCriteria.add(Restrictions.le(Loan.START_DATE_REF, endDate));
            }
        }

        if (filterConfigs != null && filterConfigs.size() > 0) {
            filterCriterion = PigeHibernateUtil.buildFilterCriterion(filterConfigs);
            if (filterCriterion != null) {
                loansCriteria.add(filterCriterion);
            }
        }

        usersCriteria = loansCriteria.createCriteria(Loan.USER_REF, "usr", Criteria.LEFT_JOIN);

        if (userParam != null) {
            String userScope = null;
            itr = userParam.iterator();
            while (itr.hasNext()) {
                fc = itr.next();
                if (fc.getField().equals("scope")) {
                    userScope = (String) fc.getValue();
                    itr.remove();
                    break;
                }
            }
            if (userScope != null && !userScope.isEmpty() && !userScope.equals("*")) {
                logger.debug(
                        "Restriction de la recherche sur un usager " + "spcifique: [" + userScope + "] ...");
                usersCriteria.add(Restrictions.like(User.IDENTIFIER_REF, userScope, MatchMode.EXACT));
            } else {
                logger.debug("Restriction de la recherche sur un ou des " + "usager spcifique...");
                filterCriterion = PigeHibernateUtil.buildFilterCriterion(userParam);
                if (filterCriterion != null) {
                    usersCriteria.add(filterCriterion);
                }
            }
        }

        loanCount = (Integer) loansCriteria.setProjection(Projections.rowCount()).uniqueResult();

        offset = configs.getOffset();
        limit = loanCount;
        if (limit > 0 && configs.getLimit() > 0) {
            limit = Math.min(configs.getLimit(), limit);
        }

        logger.debug("Paramtres d'extraction des donnes: dpart=" + offset + ", max=" + limit + "] ...");

        loansCriteria.setProjection(null);
        loansCriteria.setResultTransformer(Criteria.ROOT_ENTITY);

        loans = (List) loansCriteria.addOrder(Order.asc("usr." + User.LOAN_NO_REF)).setFirstResult(offset)
                .setMaxResults(limit).list();

        tx.commit();
        logger.debug("Rcupration russie!");
    } catch (Exception hex) {
        logger.error(hex);
        if (tx != null) {
            tx.rollback();
        }
    } finally {
        if (session != null) {
            session.close();
        }
    }

    if (loans == null) {
        loans = new ArrayList();
    }

    return new BasePagingLoadResult(loans, offset, loanCount);
}

From source file:ca.qc.cegepoutaouais.tge.pige.server.ManagementServiceImpl.java

License:Open Source License

@Override
public PagingLoadResult<Role> getAllRole(PagingLoadConfig config) {

    logger.debug("Rcupration de tous les rles [Pagination: dpart=" + config.getOffset() + ", max="
            + config.getLimit() + "] ...");

    Session session = null;//from   ww w  . ja v a2s .  c  o  m
    Transaction tx = null;
    Integer roleCount = 0;
    Integer limit = 0;
    Integer start = 0;
    List<Role> roles = null;

    try {

        session = PigeHibernateUtil.openSession();
        tx = session.beginTransaction();

        roleCount = (Integer) session.createCriteria(Role.class).setProjection(Projections.rowCount())
                .uniqueResult();

        start = config.getOffset();
        limit = roleCount;
        if (config.getLimit() > 0) {
            limit = Math.min(start + config.getLimit(), limit);
        }

        roles = (List) session.createCriteria(Role.class).setFirstResult(start).setMaxResults(limit).list();

        tx.commit();
        logger.debug("Rcupration russie!");
    } catch (Exception hex) {
        logger.error(hex);
        if (tx != null) {
            tx.rollback();
        }
    } finally {
        if (session != null) {
            session.close();
        }
    }

    return new BasePagingLoadResult(roles, config.getOffset(), roleCount);

}

From source file:ca.qc.cegepoutaouais.tge.pige.server.ManagementServiceImpl.java

License:Open Source License

@Override
public List<Category> getCategories(Category parent, Boolean includeUnclassified) throws PigeException {

    logger.debug("Rcupration des catgories...");

    Transaction tx = null;/*from   w ww.  j  a  v  a2  s.c  om*/
    List<Category> categories = null;
    Session session = null;

    try {
        session = PigeHibernateUtil.openSession();
        tx = session.beginTransaction();

        Criteria criteria = session.createCriteria(Category.class);
        if (parent != null) {
            logger.debug("category != null: " + parent.getName());
            criteria.add(Restrictions.eq(Category.PARENT_REF, parent));
        } else {
            criteria.add(Restrictions.isNull(Category.PARENT_REF));
        }
        criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

        categories = (List) criteria.addOrder(Order.asc(Category.NAME_REF)).list();

        if (categories != null) {
            for (Category c : categories) {
                Criteria itemCrit = session.createCriteria(Item.class);
                itemCrit.createCriteria(Item.CATEGORIES_REF)
                        .add(Restrictions.like(Category.PATH_REF, c.getPath(), MatchMode.START));
                itemCrit.setProjection(Projections.distinct(Projections.rowCount()));
                c.setItemCount((Integer) itemCrit.uniqueResult());
            }
        }

        //  la racine seulement.
        if (includeUnclassified && parent == null) {
            Category unclassified = new Category();
            unclassified.setId(Category.UNCLASSIFIED_CATEGORY_ID);
            Criteria itemCrit = session.createCriteria(Item.class);
            itemCrit.add(Restrictions.sizeEq(Item.CATEGORIES_REF, 0));
            itemCrit.setProjection(Projections.distinct(Projections.rowCount()));
            unclassified.setItemCount((Integer) itemCrit.uniqueResult());
            categories.add(unclassified);
        }

        tx.commit();
        logger.debug("Rcupration russie!");
    } catch (Exception hex) {
        logger.error(hex);
        if (tx != null) {
            tx.rollback();
        }
    } finally {
        if (session != null) {
            session.close();
        }
    }

    return categories;
}

From source file:ca.qc.cegepoutaouais.tge.pige.server.report.ReportDataProvider.java

License:Open Source License

/**
 * Permet d'obtenir des donnes de la base de donnes afin de gnrer
 * des statistiques utiles pour les rapports.
 *
 * @param stats map contenant les statistiques gnres
 */// ww w.java 2s  . co  m
public void calculateLoanStatistics(Map stats) {

    Transaction tx = null;
    Session session = null;

    try {
        session = PigeHibernateUtil.openSession();
        tx = session.beginTransaction();

        Integer totalCount = (Integer) session.createCriteria(Loan.class).setProjection(Projections.rowCount())
                .uniqueResult();

        Integer lentCount = (Integer) session.createCriteria(Loan.class)
                .add(Restrictions.eq(Loan.STATUS_REF, LoanStatus.STATUS_LENT))
                .setProjection(Projections.rowCount()).uniqueResult();

        Integer lateCount = (Integer) session.createCriteria(Loan.class)
                .add(Restrictions.eq(Loan.STATUS_REF, LoanStatus.STATUS_LATE))
                .setProjection(Projections.rowCount()).uniqueResult();

        tx.commit();

        stats.put("total-count", totalCount);
        stats.put("lent-count", lentCount + lateCount);
        stats.put("late-count", lateCount);

        Float tc = new Float(totalCount);
        Float lc = new Float(lentCount + lateCount);
        Float percent = lc / tc * 100.0f;

        stats.put("percent-lent", percent);

        Float lec = new Float(lentCount);
        Float lac = new Float(lateCount);
        percent = lac / (lec + lac) * 100.0f;

        stats.put("percent-late", percent);

    } catch (Exception hex) {
        logger.error(hex);
        if (tx != null) {
            tx.rollback();
        }
    } finally {
        if (session != null) {
            session.close();
        }
    }

}

From source file:ch.systemsx.cisd.openbis.generic.server.dataaccess.db.DAOUtils.java

License:Apache License

/**
 * Returns the number of entities that the given <var>critera</var> will return.
 *///from   www . jav a 2 s. c  om
static int getCount(final Criteria criteria) {
    int count = (Integer) criteria.setProjection(Projections.rowCount()).uniqueResult();
    // Undo the rowCount projection
    criteria.setProjection(null);
    criteria.setResultTransformer(Criteria.ROOT_ENTITY);
    return count;
}

From source file:ch.systemsx.cisd.openbis.generic.server.dataaccess.db.EntityPropertyTypeDAO.java

License:Apache License

public void fillTermUsageStatistics(List<VocabularyTermWithStats> termsWithStats, VocabularyPE vocabulary) {
    assert termsWithStats != null : "Unspecified terms.";
    assert vocabulary != null : "Unspecified vocabulary.";
    assert termsWithStats.size() == vocabulary.getTerms()
            .size() : "Sizes of terms to be filled and vocabulary terms don't match.";

    Map<Long, VocabularyTermWithStats> termsById = new HashMap<Long, VocabularyTermWithStats>(
            termsWithStats.size());//from   w ww .java  2s  .c o m
    for (VocabularyTermWithStats termWithStats : termsWithStats) {
        Long id = termWithStats.getTerm().getId();
        termsById.put(id, termWithStats);
    }

    final DetachedCriteria criteria = DetachedCriteria.forClass(entityKind.getEntityPropertyClass());
    // alias is the easiest way to restrict on association using criteria
    criteria.createAlias("vocabularyTerm", "term");
    criteria.add(Restrictions.eq("term.vocabularyInternal", vocabulary));
    ProjectionList projectionList = Projections.projectionList();
    projectionList.add(Projections.rowCount());
    projectionList.add(Projections.groupProperty("term.id"));
    criteria.setProjection(projectionList);

    final List<Object[]> results = cast(getHibernateTemplate().findByCriteria(criteria));

    for (Object[] result : results) {
        Integer numberOfUsages = (Integer) result[0];
        Long termId = (Long) result[1];
        termsById.get(termId).registerUsage(entityKind, numberOfUsages);
    }
}

From source file:ch.systemsx.cisd.openbis.generic.server.dataaccess.db.ExternalDataDAO.java

License:Apache License

public boolean hasExternalData(SamplePE sample) throws DataAccessException {
    final DetachedCriteria criteria = DetachedCriteria.forClass(ExternalDataPE.class);
    criteria.add(Restrictions.eq("sampleInternal", sample));
    criteria.setProjection(Projections.rowCount());
    Integer count = (Integer) getHibernateTemplate().findByCriteria(criteria).get(0);
    return count > 0;
}

From source file:chat.service.Data.java

License:LGPL

public Integer count(Criteria<?> c) {
    int n = (Integer) c.setProjection(Projections.rowCount()).uniqueResult();
    c.setProjection(null);
    return n;
}

From source file:chat.service.DoChat.java

License:LGPL

/**
 * also persist SO// www. j a  va 2  s.  c o m
 *
 * @return with {@link Chat#datime}
 */
@Service
public Chat post(Chat c, Input.Upload smiley) throws Exception {
    c.out = new User().id(sess.me);
    validate(c);

    Criteria<?> t = data.criteria(User.class).setProjection(Projections.rowCount());
    t.add(Restrictions.idEq(c.in.id));
    t.createCriteria("friends").add(Restrictions.idEq(c.out.id));
    if ((Integer) t.uniqueResult() == 0)
        throw err("You must be his/her friend");
    c.datime = new Date();
    while (smiley != null && smiley.available() > 0) {
        final Bytes b = new Bytes(smiley, false);
        final ByteArrayInputStream in = new ByteArrayInputStream(b.bytes, b.beginBi, b.byteN());
        Smiley s = new Smiley();
        s.in = c.in;
        s.image = new Blob() {
            @Override
            public long length() {
                return b.byteN();
            }

            @Override
            public void truncate(long pos) {
                throw new UnsupportedOperationException();
            }

            @Override
            public byte[] getBytes(long pos, int len) {
                throw new UnsupportedOperationException();
            }

            @Override
            public int setBytes(long pos, byte[] bytes) {
                throw new UnsupportedOperationException();
            }

            @Override
            public int setBytes(long pos, byte[] bytes, int i, int j) {
                throw new UnsupportedOperationException();
            }

            @Override
            public long position(byte[] bytes, long pos) {
                throw new UnsupportedOperationException();
            }

            @Override
            public InputStream getBinaryStream() {
                in.reset();
                return in;
            }

            @Override
            public OutputStream setBinaryStream(long pos) {
                throw new UnsupportedOperationException();
            }

            @Override
            public long position(Blob blob, long pos) {
                throw new UnsupportedOperationException();
            }

            @Override
            public void free() {
            }

            @Override
            public InputStream getBinaryStream(long pos, long length) {
                throw new UnsupportedOperationException();
            }
        };
        s.type = smiley.type();
        if (c.smileys == null)
            c.smileys = new ArrayList<Smiley>();
        c.smileys.add(s);
        smiley.next();
    }
    data.save(c);
    return c;
}

From source file:chiron.maxscore.dao.impl.BaseDAOImpl.java

/**
 * ??//from w ww . ja v a  2  s .c om
 *
 * @param criteria ?
 * @return 
 */
@Override
public int count(DetachedCriteria criteria) {
    Session session = sessionFactory.getCurrentSession();
    return ((Number) criteria.setProjection(Projections.rowCount()).getExecutableCriteria(session)
            .uniqueResult()).intValue();
}