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:co.com.codesoftware.logic.productos.FacturaCompraLogic.java

/**
 * funcion que consulta el maximo de la tabla de pagos
 *
 * @return//from w  ww. j a v  a  2s  .  c  o  m
 */
public Integer selecMaxPago() {
    Long resultado = new Long(1);
    try {

        initOperation();
        resultado = (Long) sesion.createCriteria(PagoFacCompraEntity.class)
                .setProjection(Projections.rowCount()).uniqueResult() + 1;
        close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return resultado.intValue();
}

From source file:co.com.codesoftware.logica.inventario.ProductosParamLogica.java

/**
 * metodo que valida si el producto esta parametrizado
 * @param idProducto/*from   ww  w.j  av a 2s  .  c  om*/
 * @return 
 */
public Integer verificaProductoParam(Integer idProducto) {
    Integer rta = 0;
    try {
        initOperation();
        rta = (Integer) sesion.createCriteria(ProductosParamEntity.class).setProjection(Projections.rowCount())
                .add(Restrictions.eq("idProducto", idProducto)).uniqueResult().hashCode();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return rta;
}

From source file:co.webmonkey.models.management.WebsiteManagement.java

public boolean isInstalled() {
    session.getTransaction().begin();/*  www  . ja  v a 2  s  .  c  o m*/
    Criteria cr = session.createCriteria(Users.class);
    cr.setProjection(Projections.rowCount());
    int nb = ((Long) cr.uniqueResult()).intValue();
    session.getTransaction().commit();
    return nb > 0;
}

From source file:com.abiquo.abiserver.commands.UserCommand.java

License:Mozilla Public License

/**
 * Returns a list of users stored in the Data Base
 * //from  www  . java2s  .  c  om
 * @param userSession
 * @param userListOptions an UserListOptions object containing the options to retrieve the list
 *            of users
 * @return A DataResult object containing an UserListResult object with an ArrayList of User and
 *         the number of total users
 */
@SuppressWarnings("unchecked")
protected DataResult<UserListResult> getUsers(UserSession userSession, UserListOptions userListOptions) {
    DataResult<UserListResult> dataResult = new DataResult<UserListResult>();
    UserListResult userListResult = new UserListResult();

    Session session = null;
    Transaction transaction = null;

    try {
        session = HibernateUtil.getSession();
        transaction = session.beginTransaction();

        // Getting the user that called this method
        UserHB userHB = (UserHB) session.createCriteria(UserHB.class)
                .add(Restrictions.eq("user", userSession.getUser())).uniqueResult();

        // getUsers has two different authorization resources
        // If the user who called this method, does not match the security level for the
        // authorization resource
        // USER_GET_ALL_USERS, this method will only return those users who belongs to the same
        // enterprise than
        // the user that called this method

        // Getting the authorization resource USER_GET_ALL_USERS
        AuthResourceHB authResourceHB = (AuthResourceHB) session.createCriteria(AuthResourceHB.class)
                .add(Restrictions.eq("name", "USER_GET_ALL_USERS")).uniqueResult();

        // Checking if the user has not the necessary security level to see the whole list of
        // Users. If so, we force
        // the userListOptions object to filter by the enterprise assigned to the user
        if (authResourceHB.getRoleHB().getSecurityLevel()
                .compareTo(userHB.getRoleHB().getSecurityLevel()) == -1) {
            // NOT GRANTED!
            userListOptions.setByEnterprise((Enterprise) userHB.getEnterpriseHB().toPojo());
        }

        // Creating users criteria
        Criteria usersListCriteria = session.createCriteria(UserHB.class);
        Criteria usersCountCriteria = session.createCriteria(UserHB.class);

        // Removing the users that are deleted
        usersListCriteria.add(Restrictions.eq("deleted", 0));
        usersCountCriteria.add(Restrictions.eq("deleted", 0));

        // Adding filter by name, surname or email
        Disjunction filterDisjunction = Restrictions.disjunction();
        if (userListOptions.getFilter().length() > 0) {
            filterDisjunction.add(Restrictions.like("name", '%' + userListOptions.getFilter() + '%'));
            filterDisjunction.add(Restrictions.like("surname", '%' + userListOptions.getFilter() + '%'));
            filterDisjunction.add(Restrictions.like("email", '%' + userListOptions.getFilter() + '%'));
        }
        usersListCriteria.add(filterDisjunction);
        usersCountCriteria.add(filterDisjunction);

        // Adding filter by Enterprise
        if (userListOptions.getByEnterprise() != null) {
            usersListCriteria.add(Restrictions.eq("enterpriseHB",
                    (EnterpriseHB) userListOptions.getByEnterprise().toPojoHB()));
            usersCountCriteria.add(Restrictions.eq("enterpriseHB",
                    (EnterpriseHB) userListOptions.getByEnterprise().toPojoHB()));
        }

        // Adding order
        // Little fix to match the object used in Hibernate
        if (userListOptions.getOrderBy().compareTo("role") == 0)
            userListOptions.setOrderBy("roleHB");

        Order order;
        if (userListOptions.getAsc())
            order = Order.asc(userListOptions.getOrderBy());
        else
            order = Order.desc(userListOptions.getOrderBy());

        usersListCriteria.addOrder(order);
        usersCountCriteria.addOrder(order);

        // Adding filter to get only the users that currently have an active session
        if (userListOptions.getLoggedOnly()) {
            ArrayList<String> currentLoggedUsers = (ArrayList<String>) session
                    .createSQLQuery("SELECT user FROM session WHERE expireDate > CURRENT_TIMESTAMP()").list();
            usersListCriteria.add(Restrictions.in("user", currentLoggedUsers));
            usersCountCriteria.add(Restrictions.in("user", currentLoggedUsers));
        }

        // Once we have the criteria...
        // 1. Getting the total number of users that match userListOptions
        Integer totalUsers = (Integer) usersCountCriteria.setProjection(Projections.rowCount()).uniqueResult();

        // 2. Getting the list of users, applying an offset and a max of results
        ArrayList<UserHB> usersHB = (ArrayList<UserHB>) usersListCriteria
                .setFirstResult(userListOptions.getOffset()).setMaxResults(userListOptions.getLength()).list();

        // Building result
        ArrayList<User> usersList = new ArrayList<User>();
        for (UserHB userToReturnHB : usersHB) {
            usersList.add((User) userToReturnHB.toPojo());
        }

        userListResult.setTotalUsers(totalUsers);
        userListResult.setUsersList(usersList);

        transaction.commit();
    } catch (Exception e) {
        if (transaction != null && transaction.isActive())
            transaction.rollback();

        this.errorManager.reportError(resourceManager, dataResult, "getUsers", e);

        return dataResult;
    }

    dataResult.setData(userListResult);
    dataResult.setSuccess(true);
    dataResult.setMessage(UserCommand.resourceManager.getMessage("getUsers.success"));

    return dataResult;
}

From source file:com.abiquo.abiserver.commands.UserCommand.java

License:Mozilla Public License

/**
 * Gets the List of enterprises from the Data Base. Enterprises marked as deleted will not be
 * returned/*from   w ww . j av a2 s.co  m*/
 * 
 * @param userSession A UserSession object containing the information of the user that called
 *            this method
 * @param enterpriseListOptions an UserListOptions object containing the options to retrieve the
 *            list of users
 * @return A DataResult object containing an EnterpriseListResult object
 */
@SuppressWarnings("unchecked")
protected DataResult<EnterpriseListResult> getEnterprises(UserSession userSession,
        EnterpriseListOptions enterpriseListOptions) {
    DataResult<EnterpriseListResult> dataResult = new DataResult<EnterpriseListResult>();

    Session session = null;
    Transaction transaction = null;

    try {
        session = HibernateUtil.getSession();
        transaction = session.beginTransaction();

        ArrayList<Enterprise> enterpriseList = new ArrayList<Enterprise>();
        Integer totalEnterprises = 0;

        // Getting the user that called this method
        UserHB userHB = (UserHB) session.createCriteria(UserHB.class)
                .add(Restrictions.eq("user", userSession.getUser())).uniqueResult();

        // getEnterprises has two different authorization resources
        // If the user who called this method, does not match the security level for the
        // authorization resource
        // ENTERPRISE_GET_ALL_ENTERPRISES, this method will only return the enterprise to which
        // the user belongs

        // Getting the authorization resources ENTERPRISE_GET_ALL_ENTERPRISES
        AuthResourceHB authResourceHB = (AuthResourceHB) session.createCriteria(AuthResourceHB.class)
                .add(Restrictions.eq("name", "ENTERPRISE_GET_ALL_ENTERPRISES")).uniqueResult();

        // Checking if the user has a security level equal or higher than the necessary for
        // retrieve the whole list of
        // enterprises. Tip: in securityLevel scale, 1 is the greater level of security, and 99
        // the lowest
        if (authResourceHB.getRoleHB().getSecurityLevel()
                .compareTo(userHB.getRoleHB().getSecurityLevel()) > -1) {
            // GRANTED! This User can view other Enterprises than the one to he belongs

            // Creating enterprises criteria
            Criteria enterprisesListCriteria = session.createCriteria(EnterpriseHB.class);
            Criteria enterprisesCountCriteria = session.createCriteria(EnterpriseHB.class);

            // Removing the enterprises that are deleted
            enterprisesListCriteria.add(Restrictions.eq("deleted", 0));
            enterprisesCountCriteria.add(Restrictions.eq("deleted", 0));

            // Adding filter text
            enterprisesListCriteria
                    .add(Restrictions.like("name", '%' + enterpriseListOptions.getFilter() + '%'));
            enterprisesCountCriteria
                    .add(Restrictions.like("name", '%' + enterpriseListOptions.getFilter() + '%'));

            // Adding order
            enterprisesListCriteria.addOrder(Order.asc("name"));

            // Once we have the criteria...
            // 1. Getting the total number of enterprises that match enterpriseListOptions
            totalEnterprises = (Integer) enterprisesCountCriteria.setProjection(Projections.rowCount())
                    .uniqueResult();

            // 2. Getting the list of enterprises, applying an offset and a max of results
            ArrayList<EnterpriseHB> enterpriseHBList = (ArrayList<EnterpriseHB>) enterprisesListCriteria
                    .setFirstResult(enterpriseListOptions.getOffset())
                    .setMaxResults(enterpriseListOptions.getLength()).list();

            // Building result
            for (EnterpriseHB enterpriseHB : enterpriseHBList) {
                enterpriseList.add((Enterprise) enterpriseHB.toPojo());
            }
        } else {
            // NOT GRANTED! This User can only view the Enterprise to which he belongs
            enterpriseList.add((Enterprise) userHB.getEnterpriseHB().toPojo());
            totalEnterprises = 1;
        }

        transaction.commit();

        EnterpriseListResult enterpriseListResult = new EnterpriseListResult();
        enterpriseListResult.setEnterprisesList(enterpriseList);
        enterpriseListResult.setTotalEnterprises(totalEnterprises);

        dataResult.setSuccess(true);
        dataResult.setData(enterpriseListResult);
        dataResult.setMessage(UserCommand.resourceManager.getMessage("getEnterprises.success"));
    } catch (Exception e) {
        if (transaction != null && transaction.isActive())
            transaction.rollback();

        this.errorManager.reportError(resourceManager, dataResult, "getEnterprises", e);
    }

    return dataResult;
}

From source file:com.abiquo.server.core.common.persistence.DefaultDAOBase.java

License:Open Source License

protected Long count(final Criteria criteria) {
    criteria.setProjection(Projections.rowCount());

    return (Long) criteria.uniqueResult();
}

From source file:com.abiquo.server.core.infrastructure.RepositoryDAO.java

License:Open Source License

public boolean existRepositoryInOtherDatacenter(Datacenter datacenter, String repositoryLocation) {
    Criterion notDatacenter = Restrictions.not(thisDatacenter(datacenter));
    Criteria criteria = createCriteria(notDatacenter, thisLocation(repositoryLocation));

    criteria.setProjection(Projections.projectionList().add(Projections.rowCount()));

    Long count = (Long) criteria.uniqueResult();
    return count != null && count.intValue() > 0;
}

From source file:com.abiquo.server.core.infrastructure.RepositoryDAO.java

License:Open Source License

public boolean existRepositoryInSameDatacenter(Datacenter datacenter, String repositoryLocation) {
    Criteria criteria = createCriteria(thisDatacenter(datacenter), thisLocation(repositoryLocation));
    criteria.setProjection(Projections.projectionList().add(Projections.rowCount()));

    Long count = (Long) criteria.uniqueResult();
    return count != null && count.intValue() > 0;
}

From source file:com.abssh.util.GenericDao.java

License:Apache License

/**
 * countCriteria./*from w w w .  ja  va2s .  c  o m*/
 */
@SuppressWarnings("unchecked")
protected int 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("can not throw Exception:{}", e.getMessage());
    }

    // Count
    Long ct = (Long) c.setProjection(Projections.rowCount()).uniqueResult();
    int totalCount = ct == null ? 0 : ct.intValue();

    // ?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("can not throw Exception:{}", e.getMessage());
    }

    return totalCount;
}

From source file:com.agenda.dao.GenericDaoImpl.java

public int getCountOfAll() {
    Long count;/*from  ww w  .j a  v  a  2  s . c o  m*/
    try {
        startOperation();
        count = (Long) HibernateUtil.getSession().createCriteria(clazz).setProjection(Projections.rowCount())
                .uniqueResult();
        tx.commit();
    } catch (HibernateException e) {
        count = null;
        tx.rollback();
        throw e;
    }

    if (null == count) {
        return 0;
    } else {
        return count.intValue();
    }
}