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:com.rta.vsd.data.service.impl.ViolationDataServiceImpl.java

/**
 * //from  w  ww .j a  v a 2 s  . co m
 * Gets all the violations for vehicles owned by the owner with the specified trade license number
 * 
 * @author Eldon Barrows
 * @param dsContext
 * @param retrieveArabicData
 * @param tradeLicenseNumber
 * @param paginationValues
 * @return List<VsdViolation>
 * @throws VSDDataAccessException
 */
public List<VsdViolation> getViolationsByTradeLicenseNumber(final DataServiceContext dsContext,
        boolean retrieveArabicData, String tradeLicenseNumber, PaginationParam paginationValues)
        throws VSDDataAccessException {
    logger.info("getViolationsByTradeLicenseNumber -- START");
    List<VsdViolation> violations = null;
    try {
        Session session = (Session) dsContext.getInternalContext();
        ProjectionList projectionList = Projections.projectionList();
        projectionList.add(Projections.property("v.violationId"), "violationId");
        Criteria crit = session.createCriteria(VsdViolation.class, "v")
                .add(Restrictions.eq("v.isDeleted", IDataService.BOOL_FALSE))
                .createCriteria("v.vsdInspections", "i", Criteria.LEFT_JOIN,
                        Restrictions.eq("i.isDeleted", IDataService.BOOL_FALSE))
                .createCriteria("i.vsdVehicleInfo", "vi", Criteria.LEFT_JOIN,
                        Restrictions.eq("vi.isDeleted", IDataService.BOOL_FALSE))
                .createCriteria("vi.vsdOwnerInfos", "oi", Criteria.LEFT_JOIN,
                        Restrictions.eq("oi.isDeleted", IDataService.BOOL_FALSE))
                .add(Restrictions.eq("oi.tradeLicenseNumber", tradeLicenseNumber).ignoreCase())
                .addOrder(Order.desc("v.violationId")).setProjection(Projections.distinct(projectionList));
        crit.setResultTransformer(new AliasToBeanResultTransformer(VsdViolation.class));
        if (paginationValues.getFirstResult() != null && paginationValues.getFirstResult().longValue() != -1) {
            crit.setFirstResult(paginationValues.getFirstResult().intValue());
        }
        if (paginationValues.getFetchedSize() != null && paginationValues.getFetchedSize().longValue() != -1) {
            crit.setMaxResults(paginationValues.getFetchedSize().intValue());
        }
        List list = crit.list();
        logger.debug("list.size() : " + list.size());
        Set resultSet = new HashSet(list);
        logger.debug("resultSet.size() : " + resultSet.size());
        if (resultSet.size() == 0)
            return new ArrayList();
        Iterator iterator = resultSet.iterator();
        ArrayList innerQueryList = new ArrayList<Long>();
        while (iterator.hasNext()) {
            VsdViolation violation = (VsdViolation) iterator.next();
            innerQueryList.add(violation.getViolationId());
        }
        Criteria main = session.createCriteria(VsdViolation.class, "v")
                .add(Property.forName("v.violationId").in(innerQueryList))
                .add(Restrictions.eq("v.isDeleted", IDataService.BOOL_FALSE))
                .createCriteria("v.vsdInspections", "i", Criteria.LEFT_JOIN,
                        Restrictions.eq("i.isDeleted", IDataService.BOOL_FALSE))
                .createCriteria("i.vsdVehicleInfo", "vi", Criteria.LEFT_JOIN,
                        Restrictions.eq("vi.isDeleted", IDataService.BOOL_FALSE))
                .createCriteria("vi.vsdOwnerInfos", "oi", Criteria.LEFT_JOIN,
                        Restrictions.eq("oi.isDeleted", IDataService.BOOL_FALSE))
                .add(Restrictions.eq("oi.tradeLicenseNumber", tradeLicenseNumber).ignoreCase())
                .addOrder(Order.desc("v.violationId"));
        violations = main.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list();
        logger.info("getViolationsByTradeLicenseNumber -- END");
        return violations;
    } catch (Exception ex) {
        logger.error("An error occured in getViolationsByTradeLicenseNumber()");
        throw new VSDDataAccessException(ex.getMessage(), ex);
    }
}

From source file:com.rta.vsd.data.service.impl.ViolationDataServiceImpl.java

/**
 * /*from w  w w. j a  va2  s .  c om*/
 * Gets a list of all the violations WithoutPlateConsficationInspections based on the plate details provided 
 * 
 * @author Eldon Barrows
 * @param dsContext
 * @param retrieveArabicData
 * @param vehiclePlateDetails
 * @param paginationValues
 * @return List<VsdViolation>
 * @throws VSDDataAccessException
 */
public List<VsdViolation> getViolationsWithoutPlateConsficationInspectionsByPlateDetails(
        final DataServiceContext dsContext, boolean retrieveArabicData, VehiclePlate vehiclePlateDetails,
        PaginationParam paginationValues) throws VSDDataAccessException {
    logger.info("getViolationsWithoutPlateConsficationInspectionsByPlateDetails -- START");
    List<VsdViolation> violations = null;
    try {
        Session session = (Session) dsContext.getInternalContext();
        ProjectionList projectionList = Projections.projectionList();
        projectionList.add(Projections.property("violaton.violationId"), "violationId");
        projectionList.add(Projections.property("violaton.reportedDate"), "reportedDate");
        Criteria crit = session.createCriteria(VsdViolation.class, "violaton")
                .add(Restrictions.eq("violaton.isDeleted", IDataService.BOOL_FALSE))
                .createCriteria("vsdInspections", "inspections", Criteria.LEFT_JOIN,
                        Restrictions.eq("inspections.isDeleted", IDataService.BOOL_FALSE))
                .createCriteria("vsdVehicleInfo", "vehicleInfo", Criteria.LEFT_JOIN,
                        Restrictions.eq("vehicleInfo.isDeleted", IDataService.BOOL_FALSE))
                .add(Restrictions.eq("vehicleInfo.vehiclePlateCategory", vehiclePlateDetails.getPlateCategory())
                        .ignoreCase())
                .add(Restrictions.eq("vehicleInfo.vehiclePlateCode", vehiclePlateDetails.getPlateCode())
                        .ignoreCase())
                .add(Restrictions.eq("vehicleInfo.vehiclePlateSource", vehiclePlateDetails.getPlateSource())
                        .ignoreCase())
                .add(Restrictions.eq("vehicleInfo.vehiclePlateNumber", vehiclePlateDetails.getPlateNumber())
                        .ignoreCase())
                .add(Restrictions.eq("inspections.isPlateConfiscated", Constant.FALSE))
                .addOrder(Order.desc("violaton.reportedDate"))
                .setProjection(Projections.distinct(projectionList));
        crit.setResultTransformer(new AliasToBeanResultTransformer(VsdViolation.class));
        if (paginationValues.getFirstResult() != null && paginationValues.getFirstResult().longValue() != -1) {
            crit.setFirstResult(paginationValues.getFirstResult().intValue());
        }
        if (paginationValues.getFetchedSize() != null && paginationValues.getFetchedSize().longValue() != -1) {
            crit.setMaxResults(paginationValues.getFetchedSize().intValue());
        }
        List list = crit.list();
        logger.debug("list.size() : " + list.size());
        Set resultSet = new HashSet(list);
        logger.debug("resultSet.size() : " + resultSet.size());
        if (resultSet.size() == 0)
            return new ArrayList();
        Iterator iterator = resultSet.iterator();
        ArrayList innerQueryList = new ArrayList<Long>();
        while (iterator.hasNext()) {
            VsdViolation violation = (VsdViolation) iterator.next();
            innerQueryList.add(violation.getViolationId());
        }
        Criteria main = session.createCriteria(VsdViolation.class, "violaton")
                .add(Property.forName("violaton.violationId").in(innerQueryList))
                .add(Restrictions.eq("violaton.isDeleted", IDataService.BOOL_FALSE))
                .createCriteria("vsdInspections", "inspections", Criteria.LEFT_JOIN,
                        Restrictions.eq("inspections.isDeleted", IDataService.BOOL_FALSE))
                .createCriteria("vsdVehicleInfo", "vehicleInfo", Criteria.LEFT_JOIN,
                        Restrictions.eq("vehicleInfo.isDeleted", IDataService.BOOL_FALSE))
                .add(Restrictions.eq("vehicleInfo.vehiclePlateCategory",
                        vehiclePlateDetails.getPlateCategory()))
                .add(Restrictions.eq("vehicleInfo.vehiclePlateCode", vehiclePlateDetails.getPlateCode()))
                .add(Restrictions.eq("vehicleInfo.vehiclePlateSource", vehiclePlateDetails.getPlateSource()))
                .add(Restrictions.eq("vehicleInfo.vehiclePlateNumber", vehiclePlateDetails.getPlateNumber()))
                .add(Restrictions.eq("inspections.isPlateConfiscated", Constant.FALSE))
                .addOrder(Order.desc("violaton.reportedDate"));
        violations = main.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list();
        logger.info("getViolationsWithoutPlateConsficationInspectionsByPlateDetails -- END");
        return violations;
    } catch (Exception ex) {
        logger.error("An error occured in getViolationsWithoutPlateConsficationInspectionsByPlateDetails()");
        throw new VSDDataAccessException(ex.getMessage(), ex);
    }
}

From source file:com.salesmanager.core.service.customer.impl.dao.CustomerDao.java

License:Open Source License

public SearchCustomerResponse findCustomers(SearchCustomerCriteria searchCriteria) {

    Criteria criteria = super.getSession().createCriteria(Customer.class)
            .add(Restrictions.eq("merchantId", searchCriteria.getMerchantId()))
            .addOrder(org.hibernate.criterion.Order.desc("customerLastname"))
            .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

    Criteria query = super.getSession().createCriteria(Customer.class)
            .add(Restrictions.eq("merchantId", searchCriteria.getMerchantId()))
            .addOrder(org.hibernate.criterion.Order.desc("customerLastname"))
            .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

    if (searchCriteria != null) {

        if (!StringUtils.isBlank(searchCriteria.getCustomerName())) {
            criteria.add(Restrictions.like("customerLastname", "%" + searchCriteria.getCustomerName() + "%"));
            query.add(Restrictions.like("customerLastname", "%" + searchCriteria.getCustomerName() + "%"));
        }//w w w  .j a va 2  s  . com

        if (!StringUtils.isBlank(searchCriteria.getEmail())) {
            criteria.add(Restrictions.like("customerEmailAddress", "%" + searchCriteria.getEmail() + "%"));
            query.add(Restrictions.like("customerEmailAddress", "%" + searchCriteria.getEmail() + "%"));
        }

        if (!StringUtils.isBlank(searchCriteria.getCompanyName())) {
            criteria.add(Restrictions.like("customerCompany", "%" + searchCriteria.getCompanyName() + "%"));
            query.add(Restrictions.like("customerCompany", "%" + searchCriteria.getCompanyName() + "%"));
        }

    }

    criteria.setProjection(Projections.rowCount());
    Integer count = (Integer) criteria.uniqueResult();

    criteria.setProjection(null);

    int max = searchCriteria.getQuantity();

    List list = null;
    if (count > 0) {
        query.setMaxResults(searchCriteria.getUpperLimit(count));
        query.setFirstResult(searchCriteria.getLowerLimit());
    }

    list = query.list();

    SearchCustomerResponse response = new SearchCustomerResponse();
    response.setCount(count);
    response.setCustomers(list);

    return response;

}

From source file:com.sccl.attech.common.persistence.BaseDao.java

License:Open Source License

/**
 * //w w w  .j av  a 2 s .  c  o  m
 * @param page
 * @param detachedCriteria
 * @param resultTransformer
 * @return
 */
@SuppressWarnings("unchecked")
public Page<T> find(Page<T> page, DetachedCriteria detachedCriteria, ResultTransformer resultTransformer) {
    // get count
    if (!page.isDisabled() && !page.isNotCount()) {
        page.setCount(count(detachedCriteria));
        if (page.getCount() < 1) {
            return page;
        }
    }
    Criteria criteria = detachedCriteria.getExecutableCriteria(getSession());
    criteria.setResultTransformer(resultTransformer);
    // set page   
    if (!page.isDisabled()) {
        criteria.setFirstResult(page.getFirstResult());
        criteria.setMaxResults(page.getMaxResults());
    }
    // order by
    if (StringUtils.isNotBlank(page.getOrderBy())) {
        for (String order : StringUtils.split(page.getOrderBy(), ",")) {
            String[] o = StringUtils.split(order, " ");
            //????
            String orderStr = o[0];
            if (orderStr.split("-")[0].equals("desc")) {
                criteria.addOrder(Order.desc(orderStr.split("-")[1]));
            } else {
                criteria.addOrder(Order.asc(orderStr.split("-")[1]));
            }
        }
    }
    page.setList(criteria.list());
    return page;
}

From source file:com.scit.spring.dao.GenericDAOImpl.java

public Pagina calcular(Criteria c, int pag) {
    int total = c.list().size();
    int primero = total == 0 ? 0 : (pag - 1) * MAX_RENGLONES + 1;
    int ultimo = primero - 1 + MAX_RENGLONES > total ? total : primero - 1 + MAX_RENGLONES;
    double auxMod = total % MAX_RENGLONES;
    int numPags = (int) (total / MAX_RENGLONES) + (auxMod == 0D ? 0 : 1);
    c.setMaxResults(MAX_RENGLONES);/*from ww  w . jav a 2s .  c om*/
    c.setFirstResult(primero - 1);
    return new Pagina((List<T>) c.list(), total, numPags, primero, ultimo, pag);
}

From source file:com.scopix.periscope.periscopefoundation.persistence.DAOHibernate.java

License:Open Source License

/**
 *
 * @param criteria criterio de busqueda/*  w  ww  . j  av  a 2s.co  m*/
 * @param firstResult primer resultado
 * @param maxResults numero maximo de resultados
 * @return Objeto del Tipo E
 */
public E findUniqueResultByCriteria(final DetachedCriteria criteria, final Integer firstResult,
        final Integer maxResults) {
    Assert.notNull(criteria, "DetachedCriteria must not be null");

    HibernateCallback callback = new HibernateCallback() {

        @Override
        public Object doInHibernate(Session session) {
            Criteria executableCriteria = criteria.getExecutableCriteria(session);
            if (firstResult != null) {
                executableCriteria.setFirstResult(firstResult);
            }
            if (maxResults != null) {
                executableCriteria.setMaxResults(maxResults);
            }
            return executableCriteria.uniqueResult();
        }
    };

    Object result = this.getHibernateTemplate().execute(callback);

    return (E) result;
}

From source file:com.silverpeas.mailinglist.service.model.dao.MessageDaoImpl.java

License:Open Source License

@SuppressWarnings("unchecked")
public List<Message> listAllMessagesOfMailingList(final String componentId, final int page,
        final int elementsPerPage, final OrderBy orderBy) {
    Criteria criteria = getSession().createCriteria(Message.class);
    criteria.add(Restrictions.eq("componentId", componentId));
    criteria.addOrder(orderBy.getOrder());
    int firstResult = page * elementsPerPage;
    criteria.setFirstResult(firstResult);
    criteria.setMaxResults(elementsPerPage);
    return criteria.list();
}

From source file:com.silverpeas.mailinglist.service.model.dao.MessageDaoImpl.java

License:Open Source License

@SuppressWarnings("unchecked")
public List<Message> listDisplayableMessagesOfMailingList(String componentId, final int month, final int year,
        final int page, final int elementsPerPage, final OrderBy orderBy) {
    Criteria criteria = getSession().createCriteria(Message.class);
    criteria.add(Restrictions.eq("componentId", componentId));
    criteria.add(Restrictions.eq("moderated", Boolean.TRUE));
    if (month >= 0) {
        criteria.add(Restrictions.eq("month", month));
    }//w w w  . j a  va2 s. c  om
    if (year >= 0) {
        criteria.add(Restrictions.eq("year", year));
    }
    criteria.addOrder(orderBy.getOrder());
    int firstResult = page * elementsPerPage;
    criteria.setFirstResult(firstResult);
    criteria.setMaxResults(elementsPerPage);
    return criteria.list();
}

From source file:com.silverpeas.mailinglist.service.model.dao.MessageDaoImpl.java

License:Open Source License

@SuppressWarnings("unchecked")
public List<Message> listUnmoderatedMessagesOfMailingList(String componentId, int page, int elementsPerPage,
        OrderBy orderBy) {/*from   w w w  .  j a  va 2 s .  co m*/
    Criteria criteria = getSession().createCriteria(Message.class);
    criteria.add(Restrictions.eq("componentId", componentId));
    criteria.add(Restrictions.eq("moderated", Boolean.FALSE));
    criteria.addOrder(orderBy.getOrder());
    int firstResult = page * elementsPerPage;
    criteria.setFirstResult(firstResult);
    criteria.setMaxResults(elementsPerPage);
    return criteria.list();
}

From source file:com.sjm.financialapplication.dao.impl.AccountGoalDAOImpl.java

@Override
public List<AccountGoal> getAccountGoalsById(int accountId, int start, int max) {
    Criteria criteria = getCurrentSession().createCriteria(AccountGoal.class);
    criteria.add(Restrictions.eq("account.accountId", accountId));
    criteria.setFirstResult(start);
    criteria.setMaxResults(max);/*from w  w  w.j  av  a2s . co  m*/
    return criteria.list();

}