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.floreantpos.model.dao.TicketDAO.java

License:Open Source License

public List<Ticket> findNextCustomerTickets(Integer customerId, PaginatedTableModel tableModel, String filter) {
    Session session = null;//w w w.j  a v  a 2 s  .  c  o m
    Criteria criteria = null;

    try {
        int nextIndex = tableModel.getNextRowIndex();

        session = createNewSession();
        criteria = session.createCriteria(getReferenceClass());
        criteria.add(Restrictions.eq(Ticket.PROP_CUSTOMER_ID, customerId));

        if (filter.equals(PaymentStatusFilter.OPEN)) {
            criteria.add(Restrictions.eq(Ticket.PROP_PAID, Boolean.FALSE));
            criteria.add(Restrictions.eq(Ticket.PROP_CLOSED, Boolean.FALSE));
        }

        criteria.setFirstResult(nextIndex);
        criteria.setMaxResults(tableModel.getPageSize());

        List ticketList = criteria.list();

        criteria.setProjection(Projections.rowCount());
        Integer rowCount = (Integer) criteria.uniqueResult();
        if (rowCount != null) {
            tableModel.setNumRows(rowCount);

        }

        tableModel.setCurrentRowIndex(nextIndex);

        return ticketList;

    } finally {
        closeSession(session);
    }
}

From source file:com.floreantpos.model.dao.TicketDAO.java

License:Open Source License

public List<Ticket> findPreviousCustomerTickets(Integer customerId, PaginatedTableModel tableModel,
        String filter) {/*from   w  w  w. j a  v  a2 s. c o  m*/
    Session session = null;
    Criteria criteria = null;
    try {

        int previousIndex = tableModel.getPreviousRowIndex();

        session = createNewSession();
        criteria = session.createCriteria(getReferenceClass());
        criteria.add(Restrictions.eq(Ticket.PROP_CUSTOMER_ID, customerId));

        if (filter.equals(PaymentStatusFilter.OPEN)) {
            criteria.add(Restrictions.eq(Ticket.PROP_PAID, Boolean.FALSE));
            criteria.add(Restrictions.eq(Ticket.PROP_CLOSED, Boolean.FALSE));
        }

        criteria.setFirstResult(previousIndex);
        criteria.setMaxResults(tableModel.getPageSize());

        List ticketList = criteria.list();

        criteria.setProjection(Projections.rowCount());
        Integer rowCount = (Integer) criteria.uniqueResult();
        if (rowCount != null) {
            tableModel.setNumRows(rowCount);

        }

        tableModel.setCurrentRowIndex(previousIndex);

        return ticketList;

    } finally {
        closeSession(session);
    }
}

From source file:com.floreantpos.model.dao.TicketDAO.java

License:Open Source License

public List<Ticket> findTickets(PaginatedTableModel tableModel, Date start, Date end, boolean filter) {
    Session session = null;/*from   ww  w .  j a  v a  2  s  .c o  m*/
    Criteria criteria = null;

    try {
        session = createNewSession();
        criteria = session.createCriteria(getReferenceClass());

        if (filter) {
            updateCriteriaFilters(criteria);
        }

        criteria.setFirstResult(0);
        criteria.setMaxResults(tableModel.getPageSize());
        if (start != null)
            criteria.add(Restrictions.ge(Ticket.PROP_DELIVERY_DATE, start));

        if (end != null)
            criteria.add(Restrictions.le(Ticket.PROP_DELIVERY_DATE, end));

        List ticketList = criteria.list();

        criteria.setProjection(Projections.rowCount());
        Integer rowCount = (Integer) criteria.uniqueResult();
        if (rowCount != null) {
            tableModel.setNumRows(rowCount);

        }

        tableModel.setCurrentRowIndex(0);

        return ticketList;

    } finally {
        closeSession(session);
    }
}

From source file:com.floreantpos.model.dao.TicketDAO.java

License:Open Source License

public List<Ticket> findNextTickets(PaginatedTableModel tableModel, Date start, Date end, boolean filter) {
    Session session = null;/* w  ww  .ja v a2  s. c  om*/
    Criteria criteria = null;

    try {
        int nextIndex = tableModel.getNextRowIndex();

        session = createNewSession();
        criteria = session.createCriteria(getReferenceClass());

        if (filter) {
            updateCriteriaFilters(criteria);
        }

        criteria.setFirstResult(nextIndex);
        criteria.setMaxResults(tableModel.getPageSize());

        if (start != null)
            criteria.add(Restrictions.ge(Ticket.PROP_DELIVERY_DATE, start));

        if (end != null)
            criteria.add(Restrictions.le(Ticket.PROP_DELIVERY_DATE, end));

        List ticketList = criteria.list();

        criteria.setProjection(Projections.rowCount());
        Integer rowCount = (Integer) criteria.uniqueResult();
        if (rowCount != null) {
            tableModel.setNumRows(rowCount);

        }

        tableModel.setCurrentRowIndex(nextIndex);

        return ticketList;

    } finally {
        closeSession(session);
    }
}

From source file:com.floreantpos.model.dao.TicketDAO.java

License:Open Source License

public List<Ticket> findPreviousTickets(PaginatedTableModel tableModel, Date start, Date end, boolean filter) {
    Session session = null;//  ww w . j a v  a2 s.c o  m
    Criteria criteria = null;
    try {

        int previousIndex = tableModel.getPreviousRowIndex();

        session = createNewSession();
        criteria = session.createCriteria(getReferenceClass());

        if (filter) {
            updateCriteriaFilters(criteria);
        }

        criteria.setFirstResult(previousIndex);
        criteria.setMaxResults(tableModel.getPageSize());

        if (start != null)
            criteria.add(Restrictions.ge(Ticket.PROP_DELIVERY_DATE, start));

        if (end != null)
            criteria.add(Restrictions.le(Ticket.PROP_DELIVERY_DATE, end));

        List ticketList = criteria.list();

        criteria.setProjection(Projections.rowCount());
        Integer rowCount = (Integer) criteria.uniqueResult();
        if (rowCount != null) {
            tableModel.setNumRows(rowCount);

        }

        tableModel.setCurrentRowIndex(previousIndex);

        return ticketList;

    } finally {
        closeSession(session);
    }
}

From source file:com.floreantpos.model.dao.TicketDAO.java

License:Open Source License

public void loadTickets(PaginatedTableModel tableModel, Date start, Date end) {
    Session session = null;/*from   w w  w  . ja v  a  2s  .  c  o m*/
    Criteria criteria = null;
    try {
        session = createNewSession();
        criteria = session.createCriteria(getReferenceClass());
        criteria.add(Restrictions.eq(Ticket.PROP_CLOSED, Boolean.FALSE));
        if (start != null)
            criteria.add(Restrictions.ge(Ticket.PROP_DELIVERY_DATE, start));

        if (end != null)
            criteria.add(Restrictions.le(Ticket.PROP_DELIVERY_DATE, end));

        criteria.add(Restrictions.isNotNull(Ticket.PROP_DELIVERY_DATE));
        criteria.setFirstResult(tableModel.getCurrentRowIndex());
        criteria.setMaxResults(tableModel.getPageSize());
        tableModel.setRows(criteria.list());
        return;

    } finally {
        closeSession(session);
    }
}

From source file:com.gisgraphy.domain.repository.GenericGisDao.java

License:Open Source License

/**
 * base method for all findNearest* /*w w  w  .j  a  v  a  2  s  . c o m*/
 * 
 * @param point
 *                The point from which we want to find GIS Object
 * @param pointId
 *                the id of the point that we don't want to be include, it
 *                is used to not include the gisFeature from which we want
 *                to find the nearest
 * @param distance
 *                distance The radius in meters
 * @param firstResult
 *                the firstResult index (for pagination), numbered from 1,
 *                if < 1 : it will not be taken into account
 * @param maxResults
 *                The Maximum number of results to retrieve (for
 *                pagination), if <= 0 : it will not be taken into acount
 * @param requiredClass
 *                the class of the object to be retireved
 * @param isMunicipality whether we should filter on city that are flag as 'municipality'.
          act as a filter, if false it doesn't filters( false doesn't mean that we return non municipality)
 * @return A List of GisFeatureDistance with the nearest elements or an
 *         emptylist (never return null), ordered by distance.<u>note</u>
 *         the specified gisFeature will not be included into results
 * @see GisFeatureDistance
 * @return a list of gisFeature (never return null but an empty list)
 */
@SuppressWarnings("unchecked")
protected List<GisFeatureDistance> getNearestAndDistanceFrom(final Point point, final Long pointId,
        final double distance, final int firstResult, final int maxResults, final boolean includeDistanceField,
        final Class<? extends GisFeature> requiredClass, final boolean isMunicipality) {
    Assert.notNull(point);
    return (List<GisFeatureDistance>) this.getHibernateTemplate().execute(new HibernateCallback() {

        public Object doInHibernate(Session session) throws PersistenceException {
            Criteria criteria = session.createCriteria(requiredClass);

            if (maxResults > 0) {
                criteria = criteria.setMaxResults(maxResults);
            }
            if (firstResult >= 1) {
                criteria = criteria.setFirstResult(firstResult - 1);
            }
            criteria = criteria.add(new DistanceRestriction(point, distance));
            List<String> fieldList = IntrospectionHelper.getFieldsAsList(requiredClass);
            ProjectionList projections = ProjectionBean.fieldList(fieldList, true);
            if (includeDistanceField) {
                projections.add(SpatialProjection.distance_sphere(point, GisFeature.LOCATION_COLUMN_NAME)
                        .as("distance"));
            }
            criteria.setProjection(projections);
            if (pointId != 0) {
                // remove The From Point
                criteria = criteria.add(Restrictions.not(Restrictions.idEq(pointId)));
            }
            if (includeDistanceField) {
                criteria.addOrder(new ProjectionOrder("distance"));
            }
            if (isMunicipality && (requiredClass == City.class || requiredClass == GisFeature.class)) {
                criteria.add(Restrictions.eq(City.MUNICIPALITY_FIELD_NAME, isMunicipality));
            }

            criteria.setCacheable(true);
            List<Object[]> queryResults = criteria.list();

            String[] aliasList;
            if (includeDistanceField) {
                aliasList = (String[]) ArrayUtils.add(IntrospectionHelper.getFieldsAsArray(requiredClass),
                        "distance");
            } else {
                aliasList = IntrospectionHelper.getFieldsAsArray(requiredClass);
            }
            int idPropertyIndexInAliasList = 0;
            for (int i = 0; i < aliasList.length; i++) {
                if (aliasList[i] == "id") {
                    idPropertyIndexInAliasList = i;
                    break;
                }
            }

            boolean hasZipCodesProperty = ZipCodesAware.class.isAssignableFrom(requiredClass);
            Map<Long, Set<String>> idToZipCodesMap = null;
            if (hasZipCodesProperty && queryResults.size() > 0) {
                List<Long> ids = new ArrayList<Long>();
                for (Object[] tuple : queryResults) {
                    ids.add((Long) tuple[idPropertyIndexInAliasList]);
                }
                String zipCodeQuery = "SELECT code as code,gisfeature as id FROM "
                        + ZipCode.class.getSimpleName().toLowerCase() + " zip where zip.gisfeature in (:ids)";
                Query qry = session.createSQLQuery(zipCodeQuery).addScalar("code", Hibernate.STRING)
                        .addScalar("id", Hibernate.LONG);
                qry.setCacheable(true);

                qry.setParameterList("ids", ids);
                List<Object[]> zipCodes = (List<Object[]>) qry.list();

                if (zipCodes.size() > 0) {
                    idToZipCodesMap = new HashMap<Long, Set<String>>();
                    for (Object[] zipCode : zipCodes) {
                        Long idFromZipcode = (Long) zipCode[1];
                        Set<String> zipCodesFromMap = idToZipCodesMap.get(idFromZipcode);
                        if (zipCodesFromMap == null) {
                            Set<String> zipCodesToAdd = new HashSet<String>();
                            idToZipCodesMap.put(idFromZipcode, zipCodesToAdd);
                            zipCodesFromMap = zipCodesToAdd;
                        }
                        zipCodesFromMap.add((String) zipCode[0]);
                    }
                }
            }
            List<GisFeatureDistance> results = ResultTransformerUtil.transformToGisFeatureDistance(aliasList,
                    queryResults, idToZipCodesMap, requiredClass);
            return results;
        }
    });

}

From source file:com.gisgraphy.domain.repository.OpenStreetMapDao.java

License:Open Source License

@SuppressWarnings("unchecked")
public List<StreetDistance> getNearestAndDistanceFrom(final Point point, final double distance,
        final int firstResult, final int maxResults, final StreetType streetType, final Boolean oneWay,
        final String name, final StreetSearchMode streetSearchMode, final boolean includeDistanceField) {
    if (streetSearchMode == StreetSearchMode.FULLTEXT && !GisgraphyConfig.STREET_SEARCH_FULLTEXT_MODE) {
        throw new GisgraphyException(
                "The fulltext mode has been removed in gisgraphy v 3.0 and has been replaced by fulltext webservice with placetype=street. please Consult user guide.");
    }//ww w . j  av  a 2 s.c o m
    if (name != null && streetSearchMode == null) {
        throw new IllegalArgumentException("streetSearchmode can not be null if name is provided");
    }
    if (point == null && streetSearchMode == StreetSearchMode.CONTAINS) {
        throw new IllegalArgumentException(
                "you must specify lat/lng when streetsearchmode = " + StreetSearchMode.CONTAINS);
    }
    return (List<StreetDistance>) this.getHibernateTemplate().execute(new HibernateCallback() {

        public Object doInHibernate(Session session) throws PersistenceException {
            Criteria criteria = session.createCriteria(OpenStreetMap.class);

            List<String> fieldList = IntrospectionHelper.getFieldsAsList(OpenStreetMap.class);

            ProjectionList projections = ProjectionBean.fieldList(fieldList, false);
            if (includeDistanceField && point != null) {
                projections.add(
                        //            SpatialProjection.distance_sphere(point, GisFeature.LOCATION_COLUMN_NAME).as(
                        //               "distance"));
                        SpatialProjection.distance_pointToLine(point, OpenStreetMap.SHAPE_COLUMN_NAME)
                                .as("distance"));
            }
            criteria.setProjection(projections);
            if (includeDistanceField && point != null) {
                criteria.addOrder(new ProjectionOrder("distance"));
            }
            if (maxResults > 0) {
                criteria = criteria.setMaxResults(maxResults);
            }
            if (firstResult >= 1) {
                criteria = criteria.setFirstResult(firstResult - 1);
            }
            if (point != null) {
                Polygon polygonBox = GeolocHelper.createPolygonBox(point.getX(), point.getY(), distance);
                criteria = criteria.add(new IntersectsRestriction(OpenStreetMap.SHAPE_COLUMN_NAME, polygonBox));
            }
            if (name != null) {
                if (streetSearchMode == StreetSearchMode.CONTAINS) {
                    criteria = criteria.add(Restrictions.isNotNull("name"));//optimisation!
                    criteria = criteria.add(
                            Restrictions.ilike(OpenStreetMap.FULLTEXTSEARCH_PROPERTY_NAME, "%" + name + "%"));
                    //criteria = criteria.add(new PartialWordSearchRestriction(OpenStreetMap.PARTIALSEARCH_VECTOR_COLUMN_NAME, name));
                } else if (streetSearchMode == StreetSearchMode.FULLTEXT) {
                    criteria = criteria.add(
                            new FulltextRestriction(OpenStreetMap.FULLTEXTSEARCH_VECTOR_PROPERTY_NAME, name));
                } else {
                    throw new NotImplementedException(
                            streetSearchMode + " is not implemented for street search");
                }
            }
            if (streetType != null) {
                criteria = criteria.add(Restrictions.eq("streetType", streetType));
            }
            if (oneWay != null) {
                criteria = criteria.add(Restrictions.eq("oneWay", oneWay));
            }
            criteria.setCacheable(true);
            // List<Object[]> queryResults =testCriteria.list();
            List<?> queryResults = criteria.list();

            if (queryResults != null && queryResults.size() != 0) {
                String[] propertiesNameArray;
                if (includeDistanceField && point != null) {
                    propertiesNameArray = (String[]) ArrayUtils
                            .add(IntrospectionHelper.getFieldsAsArray(OpenStreetMap.class), "distance");
                } else {
                    propertiesNameArray = IntrospectionHelper.getFieldsAsArray(OpenStreetMap.class);
                }
                List<StreetDistance> results = ResultTransformerUtil
                        .transformToStreetDistance(propertiesNameArray, queryResults);
                return results;
            } else {
                return new ArrayList<StreetDistance>();
            }

        }
    });
}

From source file:com.github.dactiv.orm.core.hibernate.support.HibernateSupportDao.java

License:Apache License

/**
 * ?Criteria,./*from w  ww  . j a v a  2s .  c o  m*/
 * 
 * @param c Hibernate Criteria
 * @param pageRequest ?
 * 
 * @return {@link Criteria}
 */
protected Criteria setPageRequestToCriteria(Criteria c, PageRequest pageRequest) {
    Assert.isTrue(pageRequest.getPageSize() > 0, "?0");

    c.setFirstResult(pageRequest.getOffset());
    c.setMaxResults(pageRequest.getPageSize());

    if (pageRequest.isOrderBySetted()) {
        for (Sort sort : pageRequest.getSort()) {
            Order order = null;
            if (sort.getDir().equals(Sort.ASC)) {
                order = Order.asc(sort.getProperty());
            } else {
                order = Order.desc(sort.getProperty());
            }
            c.addOrder(order);
        }
    }

    return c;
}

From source file:com.github.javarch.persistence.orm.hibernate.DefaultHibernateRepository.java

License:Apache License

/**
 * Busca o objeto de acordo com o objeto preenchido com os valores passado
 * como exemplo.// w  w  w.j av a  2 s . c o m
 *
 * @param objeto
 * @param indiceInicial
 * @param indiceFinal
 * @param ordenacoes
 *            lista de critrios de ordenao.
 * @return Lista de orden
 */
public <T extends Persistable<?>> List<T> findAllByExample(T objeto, PageRequest page, Order... ordenacoes) {
    Example example = createExemple(objeto);
    Criteria criteria = createCriteria((Class<T>) objeto.getClass()).add(example);
    if (page != null) {
        criteria.setFirstResult(page.getStartingAt());
        criteria.setMaxResults(page.getMaxPerPage());
    }
    addOrder(criteria, ordenacoes);

    return (List<T>) criteria.list();
}