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:com.coedil99.modello_di_dominio.impl.SagomaDAOImpl.java

public java.util.Iterator iterateSagomaByQuery(PersistentSession session, String condition, String orderBy,
        org.hibernate.LockMode lockMode) throws PersistentException {
    StringBuffer sb = new StringBuffer("From com.coedil99.modello_di_dominio.Sagoma as Sagoma");
    if (condition != null)
        sb.append(" Where ").append(condition);
    if (orderBy != null)
        sb.append(" Order By ").append(orderBy);
    try {//from w w  w.  j a  va  2 s  .  co m
        Query query = session.createQuery(sb.toString());
        query.setLockMode("Sagoma", lockMode);
        return query.iterate();
    } catch (Exception e) {
        e.printStackTrace();
        throw new PersistentException(e);
    }
}

From source file:com.corendal.netapps.wiki.writedatabeans.AbstractImage.java

License:Open Source License

public void remove(PrimaryKey referenceRequestPk) {
    /*/*from   w  w  w  .  jav a2  s .  c o  m*/
     * set the record as "done" by default
     */
    this.setIsDone(true);

    /*
     * get the JDBC data session
     */
    HibernateDataSession ds = DataSessionSetGlobal.get()
            .getSharedHibernateDataSession(DataSessionTypeConstants.WIKI_SHARED);

    /*
     * get the primary key of this image map
     */
    PrimaryKey entityPk = PrimaryKeyUtil.getAlphanumericSingleKey(EntitiesDictionary.IMAGES);
    PrimaryKey recordPk = this.getPrimaryKey();

    try {
        /*
         * get the query
         */
        Query query = ds.getWriteNamedQuery(REMOVE_1);

        /*
         * associate the query parameters
         */
        query.setParameter("childContentId", recordPk.toString());

        /*
         * execute the query
         */
        query.executeUpdate();
    } catch (Exception e) {
        /*
         * log the exception
         */
        this.setIsDone(false);
        this.appendStoreTrace(e.getMessage());
        LoggerUtil.logError(ABSTRACT_CLASS_NAME, e, entityPk, recordPk);
    }

    /*
     * remove all records in the account_role_xref
     */
    if (this.getIsDone()) {
        try {
            /*
             * get the query
             */
            Query query1 = ds.getReadNamedQuery(REMOVE_3);

            /*
             * associate the id
             */
            query1.setParameter("contentId", recordPk.toString());

            /*
             * excute the query
             */
            Iterator it = query1.iterate();

            /*
             * loop the results
             */
            while (it.hasNext()) {
                /*
                 * get the primary key of this image map
                 */
                PrimaryKey entityPk2 = PrimaryKeyUtil
                        .getAlphanumericSingleKey(EntitiesDictionary.IMAGE_VERSIONS);
                ContentVersionMapping mapping = (ContentVersionMapping) it.next();

                if (mapping != null) {
                    PrimaryKey idRecordPk = PrimaryKeyUtil.getAlphanumericSingleKey(mapping.getId());
                    /*
                     * remove all account role xref records
                     */
                    AccountRoleXrefFactory.removeAll(this, ds, entityPk2, idRecordPk);

                    StoredFileRoleXrefFactory.removeAll(this, ds, entityPk2, idRecordPk);
                }
            }
        } catch (Exception e) {
            /*
             * log the exception
             */
            this.appendLoadTrace(e.getMessage());
            LoggerUtil.logError(ABSTRACT_CLASS_NAME, e, entityPk, recordPk);
        }
    }

    /*
     * remove all records in the content_version table
     */
    if (this.getIsDone()) {
        try {
            /*
             * get the query
             */
            Query query = ds.getWriteNamedQuery(REMOVE_2);

            /*
             * associate the query parameters
             */
            query.setParameter("contentId", recordPk.toString());

            /*
             * execute the query
             */
            query.executeUpdate();
        } catch (Exception e) {
            /*
             * log the exception
             */
            this.setIsDone(false);
            this.appendStoreTrace(e.getMessage());
            LoggerUtil.logError(ABSTRACT_CLASS_NAME, e, entityPk, recordPk);
        }
    }

    /*
     * remove all records in the group_obj_role_xref
     */
    if (this.getIsDone()) {
        GroupRoleXrefFactory.removeAll(this, ds, entityPk, recordPk);
    }

    /*
     * remove all records in the content table
     */
    if (this.getIsDone()) {
        try {
            /*
             * get the hibernate session
             */
            Session session = ds.getWriteSession();

            /*
             * load the content mapping
             */
            ContentMapping mapping = (ContentMapping) session.get(DefaultContentMapping.class,
                    recordPk.toString());

            /*
             * retrieve the content from the database
             */
            if (mapping != null) {
                session.delete(mapping);
            }
        } catch (Exception e) {
            /*
             * log the exception
             */
            this.setIsDone(false);
            this.appendStoreTrace(e.getMessage());
            LoggerUtil.logError(ABSTRACT_CLASS_NAME, e, entityPk, recordPk);
        }
    }

    /*
     * refresh this image
     */
    if (this.getIsDone()) {
        PrimaryKey typePk = PrimaryKeyUtil.getAlphanumericSingleKey(
                com.corendal.netapps.framework.core.constants.EntryLogTypeConstants.DELETE);
        this.addEntryLog(entityPk, recordPk, typePk, DataSessionTypeConstants.WIKI_SHARED);
        this.clearCacheAndLoad();
    }
}

From source file:com.cyclopsgroup.tornado.hibernate.HqlLargeList.java

License:CDDL license

/**
 * Overwrite or implement method iterate()
 *
 * @see com.cyclopsgroup.waterview.LargeList#iterate(int, int, com.cyclopsgroup.waterview.LargeList.Sorting[])
 *//*ww w . j a  va  2s .co  m*/
public Iterator iterate(int startPosition, int maxRecords, Sorting[] sortings) throws Exception {
    if (StringUtils.isEmpty(hql)) {
        throw new IllegalStateException("query is still emtpy");
    }
    Session s = hibernate.getSession(dataSource);
    StringBuffer sb = new StringBuffer(hql);

    boolean first = true;
    for (int i = 0; i < sortings.length; i++) {
        Sorting sorting = sortings[i];
        if (first) {
            sb.append(" ORDER BY ");
            first = false;
        } else {
            sb.append(", ");
        }
        sb.append(sorting.getName());
        if (sorting.isDescending()) {
            sb.append(" DESC");
        }
    }

    Query q = s.createQuery(sb.toString());
    HashSet parameterNames = new HashSet();
    CollectionUtils.addAll(parameterNames, q.getNamedParameters());
    for (Iterator i = parameters.values().iterator(); i.hasNext();) {
        Parameter p = (Parameter) i.next();
        if (parameterNames.contains(p.getName())) {
            q.setParameter(p.getName(), p.getValue(), p.getType());
        }
    }
    q.setFirstResult(startPosition);
    if (maxRecords > 0) {
        q.setMaxResults(maxRecords);
    }
    return q.iterate();
}

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

License:Open Source License

public int findNumberOfOpenTickets(User user) throws PosException {
    Session session = null;/*from  w  ww  . j  av  a2s  . com*/
    Transaction tx = null;

    String hql = "select count(*) from Ticket ticket where ticket.owner=:owner and ticket." //$NON-NLS-1$
            + Ticket.PROP_CLOSED + "settled=false"; //$NON-NLS-1$
    int count = 0;
    try {
        session = getSession();
        tx = session.beginTransaction();
        Query query = session.createQuery(hql);
        query = query.setEntity("owner", user); //$NON-NLS-1$
        Iterator iterator = query.iterate();
        if (iterator.hasNext()) {
            count = ((Integer) iterator.next()).intValue();
        }
        tx.commit();
        return count;
    } catch (Exception e) {
        try {
            if (tx != null) {
                tx.rollback();
            }
        } catch (Exception e2) {
        }
        throw new PosException(Messages.getString("UserDAO.12"), e); //$NON-NLS-1$
    } finally {
        if (session != null) {
            session.close();
        }
    }
}

From source file:com.gisgraphy.dao.hibernate.HibernateConfigurationTest.java

License:Open Source License

@SuppressWarnings("unchecked")
public void testColumnMapping() throws Exception {
    Session session = sessionFactory.openSession();
    try {//from   www.  java  2  s.c  om
        Map metadata = sessionFactory.getAllClassMetadata();
        for (Object o : metadata.values()) {
            EntityPersister persister = (EntityPersister) o;
            String className = persister.getEntityName();
            log.debug("Trying select * from: " + className);
            Query q = session.createQuery("from " + className + " c");
            q.iterate();
            log.debug("ok: " + className);
        }
    } finally {
        session.close();
    }
}

From source file:com.glaf.jbpm.dao.JbpmEntityDAO.java

License:Apache License

public Paging getPage(JbpmContext jbpmContext, int currPageNo, int pageSize, SqlExecutor countExecutor,
        SqlExecutor queryExecutor) {/*from  w  ww.  java2  s  . c o  m*/
    Session session = jbpmContext.getSession();
    Paging page = new Paging();
    if (pageSize <= 0) {
        pageSize = Paging.DEFAULT_PAGE_SIZE;
    }
    if (currPageNo <= 0) {
        currPageNo = 1;
    }
    int totalCount = 0;
    if (countExecutor != null) {
        Object obj = null;
        String hql = countExecutor.getSql();
        hql = removeOrders(hql);
        Query q = session.createQuery(hql);

        Object parameter = queryExecutor.getParameter();
        if (parameter instanceof Map) {
            Map<String, Object> params = (Map<String, Object>) parameter;

            if (params != null && params.size() > 0) {
                Set<Entry<String, Object>> entrySet = params.entrySet();
                for (Entry<String, Object> entry : entrySet) {
                    String name = entry.getKey();
                    Object value = entry.getValue();
                    if (value != null) {
                        if (value instanceof Collection) {
                            q.setParameterList(name, (Collection<?>) value);
                        } else {
                            q.setParameter(name, value);
                        }
                    }
                }
            }
        }

        obj = q.iterate().next();

        if (obj instanceof Integer) {
            Integer iCount = (Integer) obj;
            totalCount = iCount.intValue();
        } else if (obj instanceof Long) {
            Long iCount = (Long) obj;
            totalCount = iCount.intValue();
        } else if (obj instanceof BigDecimal) {
            BigDecimal bg = (BigDecimal) obj;
            totalCount = bg.intValue();
        } else if (obj instanceof BigInteger) {
            BigInteger bi = (BigInteger) obj;
            totalCount = bi.intValue();
        }

    } else {
        List<Object> list = null;
        Query q = session.createQuery(queryExecutor.getSql());

        Object parameter = queryExecutor.getParameter();
        if (parameter instanceof Map) {
            Map<String, Object> params = (Map<String, Object>) parameter;

            if (params != null && params.size() > 0) {
                Set<Entry<String, Object>> entrySet = params.entrySet();
                for (Entry<String, Object> entry : entrySet) {
                    String name = entry.getKey();
                    Object value = entry.getValue();
                    if (value != null) {
                        if (value instanceof Collection) {
                            q.setParameterList(name, (Collection<?>) value);
                        } else {
                            q.setParameter(name, value);
                        }
                    }
                }
            }
        }

        list = q.list();
        if (list != null) {
            totalCount = list.size();
        }
    }

    if (totalCount == 0) {
        page.setRows(new java.util.ArrayList<Object>());
        page.setCurrentPage(0);
        page.setPageSize(0);
        page.setTotal(0);
        return page;
    }
    page.setTotal(totalCount);

    int maxPageNo = (page.getTotal() + (pageSize - 1)) / pageSize;
    if (currPageNo > maxPageNo) {
        currPageNo = maxPageNo;
    }

    Query query = session.createQuery(queryExecutor.getSql());

    Object parameter = queryExecutor.getParameter();
    if (parameter instanceof Map) {
        Map<String, Object> params = (Map<String, Object>) parameter;
        if (params != null && params.size() > 0) {
            Set<Entry<String, Object>> entrySet = params.entrySet();
            for (Entry<String, Object> entry : entrySet) {
                String name = entry.getKey();
                Object value = entry.getValue();
                if (value != null) {
                    if (value instanceof Collection) {
                        query.setParameterList(name, (Collection<?>) value);
                    } else {
                        query.setParameter(name, value);
                    }
                }
            }
        }
    }

    query.setFirstResult((currPageNo - 1) * pageSize);
    query.setMaxResults(pageSize);

    List<Object> list = query.list();
    page.setRows(list);
    page.setPageSize(pageSize);
    page.setCurrentPage(currPageNo);

    return page;
}

From source file:com.ikon.dao.NodeDocumentDAO.java

License:Open Source License

/**
 * Check for extraction queue/* ww w  .  j a v  a  2 s .  c  om*/
 */
public boolean hasPendingExtractions() throws DatabaseException {
    log.debug("hasPendingExtractions()");
    String qs = "from NodeDocument nd where nd.textExtracted=:extracted";
    Session session = null;
    Transaction tx = null;
    boolean ret = false;

    try {
        session = HibernateUtil.getSessionFactory().openSession();
        tx = session.beginTransaction();

        Query q = session.createQuery(qs);
        q.setBoolean("extracted", false);
        ret = q.iterate().hasNext();

        HibernateUtil.commit(tx);
        log.debug("hasPendingExtractions: {}", ret);
        return ret;
    } catch (HibernateException e) {
        HibernateUtil.rollback(tx);
        throw new DatabaseException(e.getMessage(), e);
    } finally {
        HibernateUtil.close(session);
    }
}

From source file:com.ikon.module.db.DbDashboardModule.java

License:Open Source License

/**
 * Get top documents/*from ww  w  .  ja  v a 2 s .  c  om*/
 */
@SuppressWarnings("unchecked")
private ArrayList<DashboardDocumentResult> getTopDocuments(String user, String source, String qs, Calendar date)
        throws RepositoryException, DatabaseException {
    log.debug("getTopDocuments({}, {}, {}, {})",
            new Object[] { user, source, qs, (date != null ? date.getTime() : "null") });
    ArrayList<DashboardDocumentResult> al = new ArrayList<DashboardDocumentResult>();
    Session session = null;
    int cont = 0;

    try {
        session = HibernateUtil.getSessionFactory().openSession();
        Query q = session.createQuery(qs).setFetchSize(MAX_RESULTS);

        if (date != null) {
            q.setCalendar("date", date);
        }

        // While there is more query results and the MAX_RESULT limit has reached
        for (Iterator<Object[]> it = q.iterate(); it.hasNext() && cont < MAX_RESULTS; cont++) {
            Object[] obj = it.next();
            String resItem = (String) obj[0];
            Calendar resDate = (Calendar) obj[1];

            try {
                NodeDocument nDoc = NodeDocumentDAO.getInstance().findByPk(resItem);
                // String docPath = NodeBaseDAO.getInstance().getPathFromUuid(nDoc.getUuid());

                // Only documents from taxonomy
                // Already filtered in the query
                // if (docPath.startsWith("/openkm:root")) {
                Document doc = BaseDocumentModule.getProperties(user, nDoc);
                DashboardDocumentResult vo = new DashboardDocumentResult();
                vo.setDocument(doc);
                vo.setDate(resDate);
                vo.setVisited(false);
                al.add(vo);
                // }
            } catch (PathNotFoundException e) {
                // Do nothing
            }
        }
    } catch (HibernateException e) {
        throw new DatabaseException(e.getMessage(), e);
    } finally {
        HibernateUtil.close(session);
    }

    log.debug("getTopDocuments: {}", al);
    return al;
}

From source file:com.isotrol.impe3.pms.core.dao.impl.DAOImpl.java

License:Open Source License

/**
 * @see com.isotrol.impe3.pms.core.dao.DAO#hasRows(org.hibernate.Query, java.util.UUID, java.util.UUID)
 *//*from  w  w  w. j a  v a 2s  .c  om*/
public boolean hasRows(Query query, UUID envId, UUID id) {
    checkNotNull(query);
    checkNotNull(envId);
    checkNotNull(id);
    query.setParameter("envId", envId).setParameter("id", id).setMaxResults(1);
    return query.iterate().hasNext();
}

From source file:com.isotrol.impe3.pms.core.dao.impl.DAOImpl.java

License:Open Source License

/**
 * @see com.isotrol.impe3.pms.core.dao.DAO#hasRows(org.hibernate.Query, java.util.UUID,
 * com.isotrol.impe3.pms.model.Entity)/*from   w w  w .j  av a2s  .co  m*/
 */
public boolean hasRows(Query query, UUID envId, Entity entity) {
    checkNotNull(query);
    checkNotNull(envId);
    checkNotNull(entity);
    query.setParameter("envId", envId).setEntity("entity", entity).setMaxResults(1);
    return query.iterate().hasNext();
}