Example usage for org.hibernate Query iterate

List of usage examples for org.hibernate Query iterate

Introduction

In this page you can find the example usage for org.hibernate Query iterate.

Prototype

Iterator<R> iterate();

Source Link

Document

Return the query results as an Iterator.

Usage

From source file:businesslogic.utility.NotificationDAO.java

public static java.util.Iterator iterateNotificationByQuery(PersistentSession session, String condition,
        String orderBy) throws PersistentException {
    StringBuffer sb = new StringBuffer("From businesslogic.utility.Notification as Notification");
    if (condition != null)
        sb.append(" Where ").append(condition);
    if (orderBy != null)
        sb.append(" Order By ").append(orderBy);
    try {/*from   ww w.  ja v  a  2s  .c om*/
        Query query = session.createQuery(sb.toString());
        return query.iterate();
    } catch (Exception e) {
        e.printStackTrace();
        throw new PersistentException(e);
    }
}

From source file:businesslogic.utility.NotificationDAO.java

public static java.util.Iterator iterateNotificationByQuery(PersistentSession session, String condition,
        String orderBy, org.hibernate.LockMode lockMode) throws PersistentException {
    StringBuffer sb = new StringBuffer("From businesslogic.utility.Notification as Notification");
    if (condition != null)
        sb.append(" Where ").append(condition);
    if (orderBy != null)
        sb.append(" Order By ").append(orderBy);
    try {/*from  w w  w  .ja  v  a2  s  . c o m*/
        Query query = session.createQuery(sb.toString());
        query.setLockMode("Notification", lockMode);
        return query.iterate();
    } catch (Exception e) {
        e.printStackTrace();
        throw new PersistentException(e);
    }
}

From source file:ca.mcgill.cs.swevo.qualyzer.util.HibernateUtil.java

License:Open Source License

/**
 * //from   w ww .  j a va2  s . co m
 * Returns an int representing a count.
 * 
 * Pre-conditions:
 *   The query must be of form "select count(...) from ..."
 *   The session that created the query must be open
 *
 * @param query
 * @return
 */
public static int count(Query query) {
    return ((Number) query.iterate().next()).intValue();
}

From source file:ca.qc.cegepoutaouais.tge.pige.server.ManagementServiceImpl.java

License:Open Source License

@Override
public PagingLoadResult<Item> getItems(PagingLoadConfig configs) throws PigeException {

    PermissionHelper.checkBrowseInventoryPermission(getThreadLocalRequest());

    Transaction tx = null;/*from  w  ww. ja  va 2  s. co  m*/
    List<Item> items = null;
    Session session = null;
    Integer itemCount = 0;
    Integer offset = 0;
    Integer limit = 0;

    try {
        session = PigeHibernateUtil.openSession();
        tx = session.beginTransaction();

        //Date startDate = null;
        //Date endDate = null;

        List<FilterConfig> searchConfigs = configs.get(PIGE.SEARCH_CONFIGS);
        List<FilterConfig> fieldsConfigs = configs.get(PIGE.ITEM_FIELDS_CONFIGS);
        List<FilterConfig> stateConfigs = configs.get(PIGE.ITEM_STATE_CONFIGS);

        // Paramtres de recherche.
        Boolean requireAnd = Boolean.FALSE;
        Boolean includeAllCategories = Boolean.FALSE;
        String keyword = "";

        if (searchConfigs != null) {
            Iterator<FilterConfig> itr = searchConfigs.iterator();
            FilterConfig fc;
            while (itr.hasNext()) {
                fc = itr.next();
                if (fc.getField().equals(PIGE.KEYWORD)) {
                    keyword = (String) fc.getValue();
                    logger.debug("Extracting keyword: [" + keyword + "]...");
                } else if (fc.getField().equals(PIGE.INCLUDE_ALL_CATEGORIES)) {
                    includeAllCategories = (Boolean) fc.getValue();
                    logger.debug("Extracting includeAllCategories: [" + includeAllCategories + "]...");
                }
            }
        }

        String query = "from Item as i";
        String path;

        FilterConfig catfc = (FilterConfig) configs.get("category");
        logger.debug("Testing category filtering...");
        if (catfc != null && !includeAllCategories) {
            logger.debug("Extracting category object...");
            Object object = catfc.getValue();
            if (object != null && object instanceof Category) {
                logger.debug("Casting category object...");
                Category category = (Category) object;
                if (category.getId() != Category.UNCLASSIFIED_CATEGORY_ID) {
                    logger.debug("PATH = " + category.getPath());
                    path = prepareStringForQuery(category.getPath());
                    query += " left join i.categories as c " + "where c.path like '" + path + "%'";
                } else {
                    query += " where i.categories.size = 0";
                }
                requireAnd = Boolean.TRUE;
            }
        }

        Boolean atLeastOneCriterion = Boolean.FALSE;
        StringBuilder searchQuery = new StringBuilder("(");
        FilterConfig fc;
        if (fieldsConfigs != null && fieldsConfigs.size() > 0 && keyword != null && !keyword.isEmpty()) {
            ListIterator<FilterConfig> itr = fieldsConfigs.listIterator();
            String field;
            Boolean firstCriterion = Boolean.TRUE;
            while (itr.hasNext()) {
                fc = itr.next();
                if ((Boolean) fc.getValue()) {
                    atLeastOneCriterion = Boolean.TRUE;
                    if (firstCriterion) {
                        firstCriterion = Boolean.FALSE;
                    } else {
                        searchQuery.append(" or ");
                    }
                    field = (String) fc.getField();
                    if (field.equals(Item.QUANTITY_REF)) {
                        String mathQuery = parseMathComparisonQuery(keyword);
                        if (mathQuery != null) {
                            searchQuery.append(mathQuery);
                        } else {
                            searchQuery.append("i.").append(field).append(" like '%").append(keyword)
                                    .append("%'");
                        }
                    } else {
                        searchQuery.append("i.").append(field).append(" like '%").append(keyword).append("%'");
                    }
                }
            }
            if (atLeastOneCriterion) {
                searchQuery.append(")");
                query += (requireAnd ? " and " : " where ");
                query += searchQuery.toString();
                requireAnd = Boolean.TRUE;
            }
        }

        atLeastOneCriterion = Boolean.FALSE;
        searchQuery = new StringBuilder("(");
        if (stateConfigs != null && stateConfigs.size() > 0) {
            ListIterator<FilterConfig> itr = stateConfigs.listIterator();
            String field;
            Boolean firstCriterion = Boolean.TRUE;
            while (itr.hasNext()) {
                fc = itr.next();
                if ((Boolean) fc.getValue()) {
                    atLeastOneCriterion = Boolean.TRUE;
                    if (firstCriterion) {
                        firstCriterion = Boolean.FALSE;
                    } else {
                        searchQuery.append(" or ");
                    }
                    field = (String) fc.getField();
                    searchQuery.append("i.status='").append(field).append("'");
                }
            }
            if (atLeastOneCriterion) {
                searchQuery.append(")");
                query += (requireAnd ? " and " : " where ");
                query += searchQuery.toString();
            }
        }

        Query itemQuery = session.createQuery("select count(*) " + query);
        itemQuery.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
        itemCount = ((Long) itemQuery.iterate().next()).intValue();

        offset = configs.getOffset();
        limit = itemCount;
        if (limit > 0 && configs.getLimit() > 0) {
            limit = Math.min(configs.getLimit(), limit);
        }

        logger.debug("Paramtres d'extraction des donnes: dpart=" + offset + ", max=" + limit + "] ...");

        items = session.createQuery("select i " + query + " order by i.name asc")
                .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).setFirstResult(offset).setMaxResults(limit)
                .list();

        tx.commit();
        logger.debug("Rcupration russie!");
    } catch (Exception hex) {
        logger.error(hex);
        if (tx != null) {
            tx.rollback();
        }
    } finally {
        if (session != null) {
            session.close();
        }
    }

    if (items == null) {
        items = new ArrayList();
    }

    return new BasePagingLoadResult(items, offset, itemCount);
}

From source file:ca.qc.cegepoutaouais.tge.pige.server.ManagementServiceImpl.java

License:Open Source License

@Override
public PagingLoadResult<Maintenance> getMaintenances(PagingLoadConfig configs) throws PigeException {

    PermissionHelper.checkBrowseInventoryPermission(getThreadLocalRequest());

    Transaction tx = null;/*from w  ww  .  j a  v a  2s . c o m*/
    List<Maintenance> maintenances = null;
    Session session = null;
    Integer maintenanceCount = 0;
    Integer offset = 0;
    Integer limit = 0;

    try {
        session = PigeHibernateUtil.openSession();
        tx = session.beginTransaction();

        List<FilterConfig> searchConfigs = configs.get(PIGE.SEARCH_CONFIGS);
        List<FilterConfig> fieldsConfigs = configs.get(PIGE.MAINTENANCE_FIELDS_CONFIGS);
        List<FilterConfig> typesConfigs = configs.get(PIGE.MAINTENANCE_TYPES_CONFIGS);

        // Paramtres de recherche.
        Boolean requireAnd = Boolean.FALSE;
        Boolean hasItem = Boolean.FALSE;
        Boolean recallActivated = Boolean.FALSE;
        String keyword = "";

        if (searchConfigs != null) {
            Iterator<FilterConfig> itr = searchConfigs.iterator();
            FilterConfig fc;
            while (itr.hasNext()) {
                fc = itr.next();
                if (fc.getField().equals(PIGE.KEYWORD)) {
                    keyword = (String) fc.getValue();
                    logger.debug("Extracting keyword: [" + keyword + "]...");
                } else if (fc.getField().equals(PIGE.HAS_ITEM)) {
                    hasItem = (Boolean) fc.getValue();
                    logger.debug("Extracting hasItem: [" + hasItem + "]...");
                } else if (fc.getField().equals(PIGE.RECALL_ACTIVATED)) {
                    recallActivated = (Boolean) fc.getValue();
                    logger.debug("Extracting recallActivated: [" + recallActivated + "]...");
                }
            }
        }

        String query = "from Maintenance as m left join {fetchType} m.items as i";

        Boolean atLeastOneCriterion = Boolean.FALSE;
        StringBuilder searchQuery = new StringBuilder("(");
        FilterConfig fc;
        if (fieldsConfigs != null && fieldsConfigs.size() > 0 && keyword != null && !keyword.isEmpty()) {
            ListIterator<FilterConfig> itr = fieldsConfigs.listIterator();
            String field;
            Boolean firstCriterion = Boolean.TRUE;
            while (itr.hasNext()) {
                fc = itr.next();
                if ((Boolean) fc.getValue()) {
                    atLeastOneCriterion = Boolean.TRUE;
                    if (firstCriterion) {
                        firstCriterion = Boolean.FALSE;
                    } else {
                        searchQuery.append(" or ");
                    }
                    field = (String) fc.getField();
                    searchQuery.append("m.").append(field).append(" like '%").append(keyword).append("%'");
                }
            }
            if (atLeastOneCriterion) {
                searchQuery.append(")");
                query += " where " + searchQuery.toString();
                requireAnd = Boolean.TRUE;
            }
        }

        atLeastOneCriterion = Boolean.FALSE;
        searchQuery = new StringBuilder("(");
        if (typesConfigs != null && typesConfigs.size() > 0) {
            ListIterator<FilterConfig> itr = typesConfigs.listIterator();
            String field;
            Boolean firstCriterion = Boolean.TRUE;
            while (itr.hasNext()) {
                fc = itr.next();
                if ((Boolean) fc.getValue()) {
                    atLeastOneCriterion = Boolean.TRUE;
                    if (firstCriterion) {
                        firstCriterion = Boolean.FALSE;
                    } else {
                        searchQuery.append(" or ");
                    }
                    field = (String) fc.getField();
                    searchQuery.append("m.type='").append(field).append("'");
                }
            }
            if (atLeastOneCriterion) {
                searchQuery.append(")");
                query += (requireAnd ? " and " : " where ");
                query += searchQuery.toString();
                requireAnd = Boolean.TRUE;
            }
        }

        if (hasItem) {
            query += (requireAnd ? " and " : " where ");
            query += " m.items.size > 0";
            requireAnd = Boolean.TRUE;
        }

        if (recallActivated) {
            query += (requireAnd ? " and " : " where ");
            query += " m.useRecall = true";
        }

        Query maintenanceQuery = session.createQuery("select count(m) " + query.replace("{fetchType}", ""))
                .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

        maintenanceCount = ((Long) maintenanceQuery.iterate().next()).intValue();

        offset = configs.getOffset();
        limit = maintenanceCount;
        if (limit > 0) {
            limit = Math.min(configs.getLimit(), limit);
        }

        logger.debug("Paramtres d'extraction des donnes: dpart=" + offset + ", max=" + limit + "] ...");

        maintenances = (List) session.createQuery("select m " + query.replace("{fetchType}", "fetch"))
                .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).setFirstResult(offset).setMaxResults(limit)
                .list();

        tx.commit();
        logger.debug("Rcupration russie!");
    } catch (Exception hex) {
        logger.error(hex);
        if (tx != null) {
            tx.rollback();
        }
    } finally {
        if (session != null) {
            session.close();
        }
    }

    if (maintenances == null) {
        maintenances = new ArrayList();
    }

    return new BasePagingLoadResult(maintenances, offset, maintenanceCount);
}

From source file:ch.algotrader.dao.AbstractDao.java

License:Open Source License

protected <V> List<V> find(final EntityConverter<E, V> converter, final String queryString,
        final int maxResults, final QueryType type) {

    Query query = prepareQuery(null, queryString, maxResults, type);
    return convert(query.iterate(), converter);
}

From source file:ch.algotrader.dao.AbstractDao.java

License:Open Source License

protected <V> List<V> find(final EntityConverter<E, V> converter, final String queryString,
        final int maxResults, final QueryType type, final Object... params) {

    Query query = prepareQuery(null, queryString, maxResults, type, params);
    return convert(query.iterate(), converter);
}

From source file:ch.algotrader.dao.AbstractDao.java

License:Open Source License

protected <V> List<V> find(final EntityConverter<E, V> converter, final String queryString,
        final int maxResults, final QueryType type, final NamedParam... params) {

    Query query = prepareQuery(null, queryString, maxResults, type, params);
    return convert(query.iterate(), converter);
}

From source file:ch.algotrader.dao.AbstractDao.java

License:Open Source License

protected <V> List<V> find(final EntityConverter<E, V> converter, final String queryString,
        final QueryType type) {

    Query query = prepareQuery(null, queryString, type);
    return convert(query.iterate(), converter);
}

From source file:ch.algotrader.dao.AbstractDao.java

License:Open Source License

protected <V> List<V> find(final EntityConverter<E, V> converter, final String queryString,
        final QueryType type, final Object... params) {

    Query query = prepareQuery(null, queryString, type, params);
    return convert(query.iterate(), converter);
}