Example usage for org.hibernate Criteria setProjection

List of usage examples for org.hibernate Criteria setProjection

Introduction

In this page you can find the example usage for org.hibernate Criteria setProjection.

Prototype

public Criteria setProjection(Projection projection);

Source Link

Document

Used to specify that the query results will be a projection (scalar in nature).

Usage

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 w w . j a  v a  2 s  .  co  m
    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:ch.qos.logback.audit.persistent.AuditEventDAO.java

License:Open Source License

@SuppressWarnings("unchecked")
static public List<Object[]> findMaxObject() throws HibernateException {
    Session s = null;/*from  w ww  . jav a2  s  .  com*/
    try {
        s = openSession();

        //Query q = s.createQuery("select count(ae.subject), ae.subject FROM "+ AE_CLASS + " AS ae "+
        //"GROUP BY ae.subject ORDER BY count(ae.subject) desc");

        Criteria crit = s.createCriteria(AuditEvent.class);
        crit.setProjection(Projections.projectionList().add(Projections.count("object").as("gcount"))
                .add(Projections.groupProperty("object")));
        crit.addOrder(Order.desc("gcount"));
        crit.setMaxResults(10);
        return crit.list();
    } finally {
        close(s);
    }
}

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.
 */// www  . j  a  va2s.c o  m
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:chat.service.Data.java

License:LGPL

public Integer count(Criteria<?> c) {
    int n = (Integer) c.setProjection(Projections.rowCount()).uniqueResult();
    c.setProjection(null);/*from   w  ww . ja va  2  s  .co  m*/
    return n;
}

From source file:classes.ReportAction.java

License:Apache License

public String productReport() throws Exception {
    logger.info("Starting productReport()"); //f:log

    ActionContext ac = ActionContext.getContext();
    ServletContext sc = (ServletContext) ac.get(StrutsStatics.SERVLET_CONTEXT);

    JasperReport jasperReport = JasperCompileManager
            .compileReport(sc.getResourceAsStream("/WEB-INF/classes/ProductReport.xml")); //f:jr

    Map<String, Object> parameters = new HashMap<String, Object>(); //f:jr
    parameters.put("ReportTitle", "List of Products"); //f:jr
    parameters.put("DataFile", new Date().toString()); //f:jr

    Session sess = HibernateUtil.getSessionFactory().openSession(); //f:hibernate
    Transaction t = sess.beginTransaction(); //f:hibernate

    Criteria criteria = sess.createCriteria(Product.class); //f:hibernate

    criteria.setProjection(Projections.projectionList().add(Projections.property("id"))
            .add(Projections.property("name")).add(Projections.property("price"))); //f:hibernate

    @SuppressWarnings("unchecked")
    List<Object[]> l = (List<Object[]>) criteria.list(); //f:hibernate

    t.commit(); //f:hibernate
    sess.close(); //f:hibernate

    HibernateQueryResultDataSource ds = new HibernateQueryResultDataSource(l,
            new String[] { "Id", "Name", "Price" }); //f:jr

    JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, ds); //f:jr

    byte b[] = JasperExportManager.exportReportToPdf(jasperPrint); //f:jr

    this.inputStream = new ByteArrayInputStream(b);

    logger.info("Finishing productReport()"); //f:log
    return "download";
}

From source file:classes.ReportAction.java

License:Apache License

public String customerReport() throws Exception {
    logger.info("Starting customerReport()"); //f:log

    ActionContext ac = ActionContext.getContext();
    ServletContext sc = (ServletContext) ac.get(StrutsStatics.SERVLET_CONTEXT);

    JasperReport jasperReport = JasperCompileManager
            .compileReport(sc.getResourceAsStream("/WEB-INF/classes/CustomerReport.xml")); //f:jr

    Map<String, Object> parameters = new HashMap<String, Object>(); //f:jr
    parameters.put("ReportTitle", "List of Customers"); //f:jr
    parameters.put("DataFile", new Date().toString()); //f:jr

    Session sess = HibernateUtil.getSessionFactory().openSession(); //f:hibernate
    Transaction t = sess.beginTransaction(); //f:hibernate

    Criteria criteria = sess.createCriteria(Customer.class); //f:hibernate

    criteria.setProjection(Projections.projectionList().add(Projections.property("id"))
            .add(Projections.property("name")).add(Projections.property("phone"))); //f:hibernate

    @SuppressWarnings("unchecked")
    List<Object[]> l = (List<Object[]>) criteria.list(); //f:hibernate

    t.commit(); //f:hibernate
    sess.close(); //f:hibernate

    HibernateQueryResultDataSource ds = new HibernateQueryResultDataSource(l,
            new String[] { "Id", "Name", "Phone" }); //f:jr

    JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, ds); //f:jr

    byte b[] = JasperExportManager.exportReportToPdf(jasperPrint); //f:jr

    this.inputStream = new ByteArrayInputStream(b);

    logger.info("Finishing customerReport()"); //f:log
    return "download";
}

From source file:cn.dayuanzi.dao.BaseDao.java

License:Apache License

/**
 * ??/*  ww  w .jav a2  s .c  o  m*/
 * @param criterions
 * @return
 */
public long count(final Criterion... criterions) {
    Criteria criteria = createCriteria(criterions);
    criteria.setProjection(Projections.rowCount());
    return (long) criteria.uniqueResult();
}

From source file:cn.hxh.springside.orm.hibernate.HibernateDao.java

License:Apache License

/**
 * countCriteria./*w w  w .  j a va  2s .c om*/
 */
protected long countCriteriaResult(final Criteria c) {
    CriteriaImpl impl = (CriteriaImpl) c;

    // Projection?ResultTransformer?OrderBy??,??Count?
    Projection projection = impl.getProjection();
    ResultTransformer transformer = impl.getResultTransformer();

    List<CriteriaImpl.OrderEntry> orderEntries = null;
    try {
        orderEntries = (List) ReflectionUtils.getFieldValue(impl, "orderEntries");
        ReflectionUtils.setFieldValue(impl, "orderEntries", new ArrayList());
    } catch (Exception e) {
        logger.error("??:{}", e.getMessage());
    }

    // Count
    Long totalCountObject = (Long) c.setProjection(Projections.rowCount()).uniqueResult();
    long totalCount = (totalCountObject != null) ? totalCountObject : 0;

    // ?Projection,ResultTransformerOrderBy??
    c.setProjection(projection);

    if (projection == null) {
        c.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);
    }
    if (transformer != null) {
        c.setResultTransformer(transformer);
    }
    try {
        ReflectionUtils.setFieldValue(impl, "orderEntries", orderEntries);
    } catch (Exception e) {
        logger.error("??:{}", e.getMessage());
    }

    return totalCount;
}

From source file:cn.lhfei.airqa.dao.support.Hibernate4DaoSupport.java

License:Apache License

@Override
public Page<E> findPageByCriteria(Criterion criterion, Page<E> page) {
    Criteria criteria = getCurrentSession().createCriteria(entityClass);
    int count = ((Long) criteria.setProjection(Projections.rowCount()).uniqueResult()).intValue();
    criteria.setProjection(null);/*w w w .j  av a 2  s  .c o  m*/
    if (criterion != null) {
        criteria.add(criterion);
    }
    page.setTotalCount(count);
    int startCount = (page.getCurPage() - 1) * page.getPageSize();
    int endCount = startCount + page.getPageSize();
    criteria.setFirstResult(startCount);
    criteria.setMaxResults(endCount);
    page.setResult(criteria.list());
    return page;
}

From source file:cn.lhfei.fu.orm.persistence.impl.HomeworkBaseDAOImpl.java

License:Apache License

@Override
public SearchAndCountModel<HomeworkBase> getPageAndCount(HomeworkBaseModel homeworkModel) {
    SearchAndCountModel<HomeworkBase> resultModel = new SearchAndCountModel<HomeworkBase>();
    List<HomeworkBase> list = new ArrayList<HomeworkBase>();

    //String sql = "From HomeworkBase as hb left join hb.archives with hb.className = :className ";
    Session session = null;//from  w  ww  . ja v  a 2 s  .co  m
    int total;

    try {
        session = getSessionFactory().getCurrentSession();
    } catch (HibernateException e) {
        session = getSessionFactory().openSession();
    }

    Criteria criteria = session.createCriteria(HomeworkBase.class, "homeworkBase");

    for (SimpleExpression exp : homeworkModel.wrapperFilter()) {
        criteria.add(exp);
    }

    //criteria.setFetchMode("homeworkBase.archives", FetchMode.JOIN);

    criteria.createCriteria("homeworkBase.archives", JoinType.LEFT_OUTER_JOIN);
    //      criteria.createAlias("homeworkBase.archives", "archives");

    total = ((Long) criteria.setProjection(Projections.rowCount()).uniqueResult()).intValue();

    criteria.setProjection(null);

    list = criteria.setFirstResult(homeworkModel.getFirst()).setMaxResults(homeworkModel.getPageSize())
            .setCacheable(true).list();

    resultModel.setTotal(total);
    resultModel.setRows(list);

    return resultModel;
}