Example usage for org.hibernate Criteria setFirstResult

List of usage examples for org.hibernate Criteria setFirstResult

Introduction

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

Prototype

public Criteria setFirstResult(int firstResult);

Source Link

Document

Set the first result to be retrieved.

Usage

From source file:cn.trymore.core.dao.impl.DAOGenericImpl.java

License:Open Source License

@SuppressWarnings("unchecked")
public PaginationSupport<T> findPageByCriteria(final DetachedCriteria criteria, final int pageSize,
        final int startIndex, final boolean dataFilter) throws DAOException {
    if (dataFilter && UtilString.isNotEmpty(this.getQueryFilter())) {
        criteria.add(Restrictions.sqlRestriction(this.getQueryFilter()));
        this.setQueryFilter(null);
    }// w  w w  .  ja v a2s . com

    return (PaginationSupport<T>) getHibernateTemplate().execute(new HibernateCallback() {
        public Object doInHibernate(Session session) throws HibernateException, SQLException {
            Criteria execCriteria = criteria.getExecutableCriteria(session);

            int rowCount = ((Integer) execCriteria.setProjection(Projections.rowCount()).uniqueResult())
                    .intValue();
            execCriteria.setProjection(null);
            execCriteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
            //execCriteria.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);
            execCriteria.setFirstResult(startIndex);

            if (pageSize > 0) {
                execCriteria.setMaxResults(pageSize);
            } else {
                execCriteria.setMaxResults(rowCount);
            }
            List<T> items = execCriteria.list();
            return rowCount > 0
                    ? new PaginationSupport<T>(items, rowCount, startIndex, pageSize > 0 ? pageSize : rowCount)
                    : null;
        }
    });
}

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

License:Mozilla Public License

/**
 * Returns a list of users stored in the Data Base
 * /*from  w  w  w  .  j  av  a  2 s .  c o m*/
 * @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  a  v  a  2 s  .  c  o 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.cloud.VirtualApplianceDAO.java

License:Open Source License

/**
 * @param user, only users with restricted VDCs. If no restricted then use user = null
 *///w  w  w . java 2  s  .c  o  m
public List<VirtualAppliance> findByEnterprise(final Enterprise enterprise, final FilterOptions filterOptions,
        final User user) {
    if (filterOptions == null) {
        return findByEnterprise(enterprise);
    }

    // Check if the orderBy element is actually one of the available ones
    VirtualAppliance.OrderByEnum orderByEnum = VirtualAppliance.OrderByEnum
            .valueOf(filterOptions.getOrderBy().toUpperCase());

    Integer limit = filterOptions.getLimit();
    Integer startwith = filterOptions.getStartwith();
    String filter = filterOptions.getFilter();
    boolean asc = filterOptions.getAsc();

    Criteria criteria = createCriteria(enterprise, filter, orderByEnum, asc);

    // Check if the page requested is bigger than the last one
    Long total = count(criteria);
    criteria = createCriteria(enterprise, filter, orderByEnum, asc);
    Integer totalResults = total.intValue();
    limit = limit != 0 ? limit : totalResults;
    if (limit != null) {
        criteria.setMaxResults(limit);
    }

    if (startwith >= totalResults) {
        startwith = totalResults - limit;
    }
    criteria.setFirstResult(startwith);
    criteria.setMaxResults(limit);

    if (user != null) {
        criteria.createAlias(VirtualAppliance.VIRTUAL_DATACENTER_PROPERTY, "virtualdatacenter");
        criteria.add(
                Restrictions.in("virtualdatacenter." + PersistentEntity.ID_PROPERTY, availableVdsToUser(user)));
    }

    List<VirtualAppliance> result = getResultList(criteria);

    PagedList<VirtualAppliance> page = new PagedList<VirtualAppliance>();
    page.addAll(result);
    page.setCurrentElement(startwith);
    page.setPageSize(limit);
    page.setTotalResults(totalResults);

    return page;
}

From source file:com.abiquo.server.core.cloud.VirtualApplianceDAO.java

License:Open Source License

public List<VirtualAppliance> findByVirtualDatacenter(final VirtualDatacenter virtualDatacenter,
        final FilterOptions filterOptions) {
    if (filterOptions == null) {
        return findByVirtualDatacenter(virtualDatacenter);
    }//from   w  ww  .  jav  a  2s  . co  m

    // Check if the orderBy element is actually one of the available ones
    VirtualAppliance.OrderByEnum orderByEnum = VirtualAppliance.OrderByEnum
            .valueOf(filterOptions.getOrderBy().toUpperCase());

    Integer limit = filterOptions.getLimit();
    Integer startwith = filterOptions.getStartwith();
    String filter = filterOptions.getFilter();
    boolean asc = filterOptions.getAsc();

    Criteria criteria = createCriteria(virtualDatacenter, filter, orderByEnum, asc);

    // Check if the page requested is bigger than the last one
    Long total = count(criteria);
    criteria = createCriteria(virtualDatacenter, filter, orderByEnum, asc);
    Integer totalResults = total.intValue();
    limit = limit != 0 ? limit : totalResults;
    if (limit != null) {
        criteria.setMaxResults(limit);
    }

    if (startwith >= totalResults) {
        startwith = totalResults - limit;
    }
    criteria.setFirstResult(startwith);
    criteria.setMaxResults(limit);

    List<VirtualAppliance> result = getResultList(criteria);

    PagedList<VirtualAppliance> page = new PagedList<VirtualAppliance>();
    page.addAll(result);
    page.setCurrentElement(startwith);
    page.setPageSize(limit);
    page.setTotalResults(totalResults);

    return page;
}

From source file:com.abiquo.server.core.cloud.VirtualDatacenterDAO.java

License:Open Source License

private Collection<VirtualDatacenter> findVirtualDatacentersByCriterions(final Collection<Criterion> criterions,
        final FilterOptions filterOptions) {
    Criteria criteria = getSession().createCriteria(VirtualDatacenter.class);

    for (Criterion criterion : criterions) {
        criteria.add(criterion);/*from   w  w w  .  ja v  a  2  s  .c  om*/
    }

    criteria.addOrder(Order.asc(VirtualDatacenter.NAME_PROPERTY));

    if (filterOptions != null) {
        Integer size = criteria.list().size();

        criteria.setFirstResult(filterOptions.getStartwith());
        criteria.setMaxResults(filterOptions.getLimit());

        PagedList<VirtualDatacenter> vdcList = new PagedList<VirtualDatacenter>(criteria.list());
        vdcList.setTotalResults(size);
        vdcList.setPageSize(filterOptions.getLimit() > size ? size : filterOptions.getLimit());
        vdcList.setCurrentElement(filterOptions.getStartwith());

        return vdcList;
    } else {
        return getResultList(criteria);
    }
}

From source file:com.abiquo.server.core.enterprise.EnterpriseDAO.java

License:Open Source License

public List<Enterprise> findAll(Integer firstElem, final Integer numResults) {

    // Check if the page requested is bigger than the last one
    Criteria criteria = createCriteria();
    Long total = count();/* ww w  .ja  v  a2s  . c o m*/

    if (firstElem >= total.intValue()) {
        firstElem = total.intValue() - numResults;
    }

    criteria.setFirstResult(firstElem);
    criteria.setMaxResults(numResults);

    List<Enterprise> result = getResultList(criteria);

    com.abiquo.server.core.util.PagedList<Enterprise> page = new PagedList<Enterprise>(result);
    page.setCurrentElement(firstElem);
    page.setPageSize(numResults);
    page.setTotalResults(total.intValue());

    return page;
}

From source file:com.abiquo.server.core.enterprise.EnterpriseDAO.java

License:Open Source License

public List<Enterprise> findByPricingTemplate(Integer firstElem, final PricingTemplate pt,
        final boolean included, final String filterName, final Integer numResults, final Integer idEnterprise) {
    // Check if the page requested is bigger than the last one

    Criteria criteria = createCriteria(pt, included, filterName, idEnterprise);

    Long total = count(criteria);

    if (firstElem >= total.intValue()) {
        firstElem = total.intValue() - numResults;
    }/*from   www.ja  va 2 s.  c o  m*/

    criteria = createCriteria(pt, included, filterName, idEnterprise);
    criteria.setFirstResult(firstElem);
    criteria.setMaxResults(numResults);

    List<Enterprise> result = getResultList(criteria);

    PagedList<Enterprise> page = new PagedList<Enterprise>();
    page.addAll(result);
    page.setCurrentElement(firstElem);
    page.setPageSize(numResults);
    page.setTotalResults(total.intValue());

    return page;

}

From source file:com.abiquo.server.core.enterprise.RoleDAO.java

License:Open Source License

public Collection<Role> find(final Enterprise enterprise, final String filter, final String orderBy,
        final boolean desc, final Integer offset, final Integer numResults,
        final boolean discardNullEnterprises) {
    Criteria criteria = createCriteria(enterprise, filter, orderBy, desc, discardNullEnterprises);

    Long total = count(criteria);

    criteria = createCriteria(enterprise, filter, orderBy, desc, discardNullEnterprises);

    criteria.setFirstResult(offset);
    criteria.setMaxResults(numResults);//  w w w  . j a  v a  2s . com

    List<Role> result = getResultList(criteria);

    PagedList<Role> page = new PagedList<Role>();
    page.addAll(result);
    page.setCurrentElement(offset);
    page.setPageSize(numResults);
    page.setTotalResults(total.intValue());

    return page;
}

From source file:com.abiquo.server.core.enterprise.RoleDAO.java

License:Open Source License

public Collection<Role> findExactly(final Enterprise enterprise, final String filter, final String orderBy,
        final boolean desc, final Integer offset, final Integer numResults,
        final boolean discardNullEnterprises) {
    Criteria criteria = createCriteriaExactly(enterprise, filter, orderBy, desc, discardNullEnterprises);

    Long total = count(criteria);

    criteria = createCriteriaExactly(enterprise, filter, orderBy, desc, discardNullEnterprises);

    criteria.setFirstResult(offset * numResults);
    criteria.setMaxResults(numResults);/*from   www  . j a va  2s  . co  m*/

    List<Role> result = getResultList(criteria);

    PagedList<Role> page = new PagedList<Role>();
    page.addAll(result);
    page.setCurrentElement(offset);
    page.setPageSize(numResults);
    page.setTotalResults(total.intValue());

    return page;
}