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.jaspersoft.ireport.designer.connection.JRHibernateConnection.java

License:Open Source License

@Override
public void test() throws Exception {
    try {//from  w  w w.j av a  2  s .  c o  m
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                Thread.currentThread()
                        .setContextClassLoader(IReportManager.getInstance().getReportClassLoader());
                SessionFactory hb_sessionFactory = null;
                try {
                    hb_sessionFactory = getSessionFactory();

                    // Try to execute an hibernate query...
                    Session hb_session = hb_sessionFactory.openSession();
                    Transaction transaction = hb_session.beginTransaction();

                    Query q = hb_session.createQuery("from java.lang.String s");

                    q.setFetchSize(100);
                    java.util.Iterator iterator = q.iterate();
                    // this is a stupid thing: iterator.next();

                    while (iterator.hasNext()) {
                        Object obj = iterator.next();
                    }

                    JOptionPane.showMessageDialog(Misc.getMainWindow(),
                            //I18n.getString("messages.connectionDialog.connectionTestSuccessful",
                            "Connection test successful!", "", JOptionPane.INFORMATION_MESSAGE);

                } catch (Throwable ex) {
                    ex.printStackTrace();
                    JOptionPane.showMessageDialog(Misc.getMainWindow(), ex.getMessage(), "Error",
                            JOptionPane.ERROR_MESSAGE);
                    return;
                } finally {

                }
            }
        });
    } catch (Exception ex) {
    }
}

From source file:com.jaspersoft.ireport.designer.connection.JRSpringLoadedHibernateConnection.java

License:Open Source License

@Override
public void test() throws Exception {
    try {/*from  w  ww .ja va2  s .c  o m*/
        Thread.currentThread().setContextClassLoader(IReportManager.getInstance().getReportClassLoader());

        SessionFactory sf = getSessionFactory();
        if (sf == null) {
            JOptionPane.showMessageDialog(Misc.getMainWindow(),
                    //I18n.getString("messages.connectionDialog.noSessionFactoryReturned",
                    "No session factory returned.  Check your session factory bean id against the spring configuration.",
                    "Error", JOptionPane.ERROR_MESSAGE);
        } else {

            Session hb_session = sf.openSession();
            Transaction transaction = hb_session.beginTransaction();
            Query q = hb_session.createQuery("select address as address Address as address");

            q.setFetchSize(1);
            java.util.Iterator iterator = q.iterate();
            // this is a stupid thing: iterator.next();

            String[] aliases = q.getReturnAliases();
            Type[] types = q.getReturnTypes();

            JOptionPane.showMessageDialog(Misc.getMainWindow(),
                    //I18n.getString("messages.connectionDialog.hibernateConnectionTestSuccessful",
                    "iReport successfully created a Hibernate session factory from your Spring configuration.",
                    "", JOptionPane.INFORMATION_MESSAGE);
        }
    } catch (Exception e) {
        e.printStackTrace();
        JOptionPane.showMessageDialog(Misc.getMainWindow(), e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);

    }
}

From source file:com.jaspersoft.ireport.designer.data.fieldsproviders.hibernate.HQLFieldsReader.java

License:Open Source License

public Vector readFields() throws Exception {
    prepareQuery();/*from  www  . j av  a 2s.c o  m*/

    SessionFactory hb_sessionFactory = null;
    Session hb_session = null;
    Transaction transaction = null;

    notScalars.clear();

    try {
        IReportConnection conn = IReportManager.getInstance().getDefaultConnection();
        if (!(conn instanceof JRHibernateConnection)) {
            throw new Exception("No Hibernate connection selected.");
        }

        hb_session = ((JRHibernateConnection) conn).createSession();

        if (hb_session == null) {
            throw new Exception("Problem creating the Session object for Hibernate");
        }

        transaction = hb_session.beginTransaction();
        Query q = hb_session.createQuery(getQueryString());

        Iterator paramIterator = queryParameters.keySet().iterator();

        while (paramIterator.hasNext()) {
            String hqlParamName = "" + paramIterator.next();
            setParameter(hb_session, q, hqlParamName, queryParameters.get(hqlParamName));
        }

        q.setFetchSize(1);
        java.util.Iterator iterator = q.iterate();
        // this is a stupid thing: iterator.next();

        String[] aliases = q.getReturnAliases();
        Type[] types = q.getReturnTypes();

        Vector fields = new Vector();

        for (int i = 0; i < types.length; ++i) {
            if (types[i].isComponentType() || types[i].isEntityType()) {

                // look for alias...
                String aliasName = null;
                if (aliases != null && aliases.length > i && !aliases[i].equals(i + "")) {
                    aliasName = aliases[i];
                    JRDesignField field = new JRDesignField();
                    field.setName(aliases[i]);

                    Class clazzRT = types[i].getReturnedClass();

                    if (clazzRT.isPrimitive()) {
                        clazzRT = MethodUtils.getPrimitiveWrapper(clazzRT);
                    }

                    String returnType = clazzRT.getName();

                    field.setValueClassName(returnType);
                    field.setDescription(aliases[i]);
                    fields.add(field);
                }

                // look for fields like for a javabean...
                java.beans.PropertyDescriptor[] pd = org.apache.commons.beanutils.PropertyUtils
                        .getPropertyDescriptors(types[i].getReturnedClass());

                if (aliasName != null) {
                    notScalars.add(new FieldClassWrapper(aliasName, types[i].getReturnedClass().getName()));
                } else {
                    notScalars.add(types[i].getReturnedClass().getName());
                }

                for (int nd = 0; nd < pd.length; ++nd) {
                    String fieldName = pd[nd].getName();
                    if (pd[nd].getPropertyType() != null && pd[nd].getReadMethod() != null) {
                        if (fieldName.equals("class"))
                            continue;

                        Class clazzRT = pd[nd].getPropertyType();

                        if (clazzRT.isPrimitive()) {
                            clazzRT = MethodUtils.getPrimitiveWrapper(clazzRT);
                        }

                        String returnType = clazzRT.getName();

                        JRDesignField field = new JRDesignField();
                        field.setName(fieldName);
                        field.setValueClassName(returnType);

                        if (types.length > 1 && aliasName != null) {
                            fieldName = aliasName + "." + fieldName;
                            field.setDescription(fieldName); //Field returned by " +methods[i].getName() + " (real type: "+ returnType +")");
                            field.setName(fieldName);
                        }
                        fields.add(field);
                    }
                }

            } else {
                String fieldName = types[i].getName();
                if (aliases != null && aliases.length > i && !aliases[i].equals("" + i))
                    fieldName = aliases[i];

                Class clazzRT = types[i].getReturnedClass();

                if (clazzRT.isPrimitive()) {
                    clazzRT = MethodUtils.getPrimitiveWrapper(clazzRT);
                }
                String returnType = clazzRT.getName();

                JRDesignField field = new JRDesignField();
                field.setName(fieldName);
                field.setValueClassName(returnType);
                //field.setDescription("");
                fields.add(field);
            }
        }
        /*
        else
        {
            for (int i =0; i<types.length; ++i)
            {
                if (aliases != null && aliases.length > 0 && !aliases[0].equals(""+i))
                {
                    JRField field = new JRField(aliases[i], types[i].getReturnedClass().getName());
                    field.setDescription("The whole entity/component object");
                    fields.add(field);
                            
                            
                }
                        
                        
            //    out.println(types[i].getName() + " " + types[i].getReturnedClass().getName() +  "<br>");
            }
        }
         */

        return fields;

    } catch (Exception ex) {
        ex.printStackTrace();
        throw ex;
    } finally {

        if (transaction != null)
            try {
                transaction.rollback();
            } catch (Exception ex) {
            }
        if (hb_session != null)
            try {
                hb_session.close();
            } catch (Exception ex) {
            }
    }
}

From source file:com.jdon.persistence.hibernate.HibernateTemplate.java

License:Apache License

public Iterator iterate(final String queryString, final Object[] values) throws Exception {
    return (Iterator) doHibernate(new HibernateCallback() {
        public Object execute(Session session) throws HibernateException {
            Query queryObject = session.createQuery(queryString);
            prepareQuery(queryObject);/*from  www  .ja v a  2  s.c  o m*/
            if (values != null) {
                for (int i = 0; i < values.length; i++) {
                    queryObject.setParameter(i, values[i]);
                }
            }
            return queryObject.iterate();
        }
    });
}

From source file:com.kingcore.cms.advert.dao.impl.AdvertDaoImpl.java

License:Open Source License

public int countByChannelId(int channelId) {
    String hql = "select count(*) from Content bean" + " join bean.channel channel,Channel parent"
            + " where channel.lft between parent.lft and parent.rgt" + " and channel.site.id=parent.site.id"
            + " and parent.id=:parentId";
    Query query = getSession().createQuery(hql);
    query.setParameter("parentId", channelId);
    return ((Number) (query.iterate().next())).intValue();
}

From source file:com.krawler.hql.payroll.payrollManager.java

License:Open Source License

public String getPayProcessData(HttpServletRequest request, String Cid, String st, String lim,
        Session session) {/*from  w  w  w  .j a v  a  2  s . c  o  m*/
    try {
        String Cids = AuthHandler.getCompanyid(request);
        int start = Integer.parseInt(request.getParameter("start"));
        int limit = Integer.parseInt(request.getParameter("limit"));
        String ss = request.getParameter("ss");
        ArrayList params = new ArrayList();
        JSONObject jobj = new JSONObject();
        String hql = "";
        hql = "from Template where companyid=?";
        params.add(Cid);
        if (!StringUtil.isNullOrEmpty(ss)) {
            StringUtil.insertParamSearchString(params, ss, 2);
            String searchQuery = StringUtil.getSearchString(ss, "and",
                    new String[] { "designationid.value", "templatename" });
            hql += searchQuery;
        }
        hql += " order by designationid.value";
        List tabledata = HibernateUtil.executeQuery(session, hql, params.toArray());
        int count = tabledata.size();
        List lst = HibernateUtil.executeQueryPaging(session, hql, params.toArray(),
                new Integer[] { start, limit });
        int cnt = lst.size();

        for (int i = 0; i < lst.size(); i++) {
            masterDB.Template wage = (masterDB.Template) lst.get(i);
            JSONObject jobjinloop = new JSONObject();
            jobjinloop.put("TempID", wage.getTemplateid());
            jobjinloop.put("TempName", wage.getTemplatename());
            jobjinloop.put("TempRange", wage.getStartrange() + " - " + wage.getEndrange());
            jobjinloop.put("GroupId", wage.getDesignationid() != null ? wage.getDesignationid().getId() : "");
            jobjinloop.put("GroupName",
                    wage.getDesignationid() != null ? wage.getDesignationid().getValue() : "");
            Query queryTax = session
                    .createQuery("select count(*) from Templatemaptax as t where t.template.templateid='"
                            + wage.getTemplateid() + "'");
            Iterator iteratorTax = queryTax.iterate();
            Object taxcount = iteratorTax.next();
            jobjinloop.put("NosTax", taxcount.toString());
            queryTax = session
                    .createQuery("select count(*) from Templatemapwage as t where t.template.templateid='"
                            + wage.getTemplateid() + "'");
            iteratorTax = queryTax.iterate();
            taxcount = iteratorTax.next();
            jobjinloop.put("NosWage", taxcount.toString());
            queryTax = session
                    .createQuery("select count(*) from Templatemapdeduction as t where t.template.templateid='"
                            + wage.getTemplateid() + "'");
            iteratorTax = queryTax.iterate();
            taxcount = iteratorTax.next();
            jobjinloop.put("NosDeduc", taxcount.toString());
            jobj.append("data", jobjinloop);
        }
        if (lst.size() == 0) {
            jobj.put("data", "");
        }
        jobj.put("success", true);
        JSONObject jobj1 = new JSONObject();
        jobj1.put("valid", true);
        jobj.put("totalcount", count);
        jobj1.put("data", jobj);
        return (jobj1.toString());
    } catch (Exception se) {
        return ("failed");
    } finally {
    }
}

From source file:com.leixl.easyframework.system.dao.impl.EUserDaoImpl.java

License:Open Source License

public int countByUsername(String username) {
    String hql = "select count(*) from EUser bean where bean.username=:username";
    Query query = getSession().createQuery(hql);
    query.setParameter("username", username);
    return ((Number) query.iterate().next()).intValue();
}

From source file:com.leixl.easyframework.system.dao.impl.EUserDaoImpl.java

License:Open Source License

public int countMemberByUsername(String username) {
    String hql = "select count(*) from EUser bean where bean.username=:username and bean.admin=false";
    Query query = getSession().createQuery(hql);
    query.setParameter("username", username);
    return ((Number) query.iterate().next()).intValue();
}

From source file:com.leixl.easyframework.system.dao.impl.EUserDaoImpl.java

License:Open Source License

public int countByEmail(String email) {
    String hql = "select count(*) from EUser bean where bean.email=:email";
    Query query = getSession().createQuery(hql);
    query.setParameter("email", email);
    return ((Number) query.iterate().next()).intValue();
}

From source file:com.lyh.licenseworkflow.dao.EnhancedHibernateDaoSupport.java

/**
 * ?????//from   w w  w  . j a va2 s .  com
 *
 * @param start 
 * @param limit 
 * @param hql   ?Hql?
 * @return
 */
public Object[] getFiexedObjectsInPage(final int start, final int limit, final String hql) {
    return (Object[]) getHibernateTemplate().execute(new HibernateCallback() {
        public Object doInHibernate(Session session) {
            String countHql = "select count(id) " + hql;
            Query countQuery = session.createQuery(countHql);
            int size = ((Long) countQuery.iterate().next()).intValue();

            Query query = session.createQuery(hql);
            query.setFirstResult(start);
            query.setMaxResults(limit);
            return new Object[] { size, query.list() };
        }
    });
}