Example usage for org.hibernate Query setFirstResult

List of usage examples for org.hibernate Query setFirstResult

Introduction

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

Prototype

@Override
    Query<R> setFirstResult(int startPosition);

Source Link

Usage

From source file:br.luck.dal.LotofacilModelDAO.java

@Override
public List<LotofacilModel> listarModalidade(int first, int pageSize) {
    Query query;
    query = getSession().createQuery(Queries.RETORNA_TODOS_CONCURSOS_LOTOFACIL);
    query.setFirstResult(first);
    query.setMaxResults(pageSize);//from w  w w  .  j  av  a 2  s.com

    return query.list();
}

From source file:br.luck.dal.LotomaniaModelDAO.java

@Override
public List<LotomaniaModel> listarModalidade(int first, int pageSize) {
    Query query;
    query = getSession().createQuery(Queries.RETORNA_TODOS_CONCURSOS_LOTOMANIA);
    query.setFirstResult(first);
    query.setMaxResults(pageSize);/* ww  w. j av a 2s  .c  om*/

    return query.list();
}

From source file:br.luck.dal.MegasenaModelDAO.java

@Override
public List<MegasenaModel> listarModalidade(int first, int pageSize) {
    Query query;
    query = getSession().createQuery(Queries.RETORNA_TODOS_CONCURSOS_MEGASENA);
    query.setFirstResult(first);
    query.setMaxResults(pageSize);/*from w w w  .j a v a 2 s .  c o  m*/

    return query.list();
}

From source file:br.sp.telesul.dao.FuncionarioDAOImpl.java

@Override
public FilterReturn searchPage(int pageNumber, int pageSize, String filter) {
    String countQ = "Select count (f.id) from Funcionario f";
    Session session = this.sessionFactory.getCurrentSession();

    Query countQuery = session.createQuery(countQ);
    Long countResults = (Long) countQuery.uniqueResult();

    int lastPageNumber = (int) ((countResults / pageSize) + 1);

    FilterReturn filterReturn = new FilterReturn();
    filterReturn.setTotalEntities(countResults);

    Query selectQuery = session.createQuery("From Funcionario f Where nome LIKE :filter");
    selectQuery.setParameter("filter", "%" + filter + "%");
    selectQuery.setFirstResult((pageNumber - 1) * pageSize);
    selectQuery.setMaxResults(pageSize);
    List<Funcionario> funcionarios = selectQuery.list();

    filterReturn.setEmployees(funcionarios);
    return filterReturn;
}

From source file:br.ufg.inf.es.fs.contpatri.web.controller.BemPatrimonialDataModel.java

License:GNU General Public License

/**
 *
 * @param first primeiro elemento da lista
 * @param pageSize tamanho da pgina/*from   w w  w .  j a va 2  s .c  om*/
 * @param sortField campo de ordenao
 * @param sortOrder ordem (decrescente, ascendente)
 * @param filters filtros
 * @return lista com os bens patrimoniais
 */
@Override
public List<BemPatrimonial> load(int first, int pageSize, String sortField, SortOrder sortOrder,
        Map<String, String> filters) {
    StringBuilder sb = new StringBuilder("from BemPatrimonial ");

    // Filtros
    if (!filters.isEmpty()) {
        sb.append("where ");
    }
    for (Iterator<String> it = filters.keySet().iterator(); it.hasNext();) {
        String filterProperty = it.next();
        String filterValue = filters.get(filterProperty);
        sb.append(filterProperty);
        sb.append(" like ");
        sb.append('\'');
        sb.append(filterValue);
        sb.append("%");
        sb.append('\'').append(' ');
        if (it.hasNext()) {
            sb.append(" and ");
        }
    }

    // Ordenao
    if (sortField != null) {
        if (sortOrder == SortOrder.ASCENDING) {
            sb.append("order by ").append(sortField).append(" asc");
        } else if (sortOrder == SortOrder.DESCENDING) {
            sb.append("order by ").append(sortField).append(" desc");
        }
    }

    // Obtendo dados
    String hql = sb.toString();
    HibernateUtil.beginTransaction();
    Query query = HibernateUtil.getSession().createQuery(hql);
    query.setFirstResult(first);
    query.setMaxResults(pageSize);
    List<BemPatrimonial> dados = bemPatrimonialDAO.findMany(query);
    HibernateUtil.commitTransaction();

    // Contagem das linhas na tabela
    HibernateUtil.beginTransaction();
    String hqlRowCount = "select count (*) ".concat(hql);
    query = HibernateUtil.getSession().createQuery(hqlRowCount);
    int rows = ((Long) query.list().get(0)).intValue();
    HibernateUtil.commitTransaction();

    setRowCount(rows);

    return dados;
}

From source file:cc.cnfc.core.orm.hibernate.HibernateDao.java

License:Open Source License

/**
 * ??HQL??/* ww  w.  j  av  a2s .c o m*/
 *
 *  1?? a)?(MySQL,Oracle,SQL
 * Server2005)?limit n,m b)?(informix,Sybase 12.5.3,SQL
 * Server)?top n c)???? 2?
 * 3?order bygroup by,having  Query q= session.createQuery(
 * "select new A(M.a,N.b) from M as M,N as N where M.id=N.id");
 *
 * @param hql
 *            HQL??Where???select???? select
 *            a,b,(select c from table1) as d from table2 ...
 *            1)(select *)??from TUser
 *            2)select userName,password from TUser;
 * @param propertyNames
 *            ???
 * @param operators
 *            ????=???null
 *            ???=, >=, <=, <>, !=, like
 * @param values
 *            ?
 * @param offset
 *            0??-1
 * @param size
 *            ??-1
 * @param isTotalSize
 *            ??true
 * @param orderBy
 *            ?,??order byorderBy="a desc,b asc",??order by a
 *            desc,b asc
 * @param groupBy
 *            ,??group by groupBy="a desc,b asc",??group by a
 *            desc,b asc
 * @param otherCause
 *            where????(order by),(group by)??(having)
 * @param isCache
 *            ?cache "group by name order by name desc"
 * @return Object[] List list = (List)Object[0]
 *         int count = ((Integer)Object[1]).intValue;
 * @throws com.rwy.base.core.exception.GenericException
 * 
 */
public Object[] query(final String hql, final String[] propertyNames, final String[] operators,
        final Object[] values, final int offset, final int size, final boolean isTotalSize,
        final String orderBy, final String groupBy, final String otherCause, final boolean isCache)
        throws DataAccessException {
    Assert.hasText(hql, "hql?");

    Query query;
    String countSql;
    String fullSql;
    Integer count = 0;
    Map map = new HashMap();
    String where = "";

    if (propertyNames != null && propertyNames.length > 0 && values != null && values.length > 0) {
        if (propertyNames.length != values.length) {
            throw new GenericException();
        }

        if (operators != null && propertyNames.length != operators.length) {
            logger.error("");
            throw new GenericException();
        }

        for (int i = 0; i <= propertyNames.length - 1; i++) {
            if ("".equals(where)) {
                where = " where ";
            } else {
                where += "and ";
            }
            if (operators != null && operators[i].equalsIgnoreCase("isnull")) {
                where += propertyNames[i] + " is null ";
            } else if (operators != null && operators[i].equalsIgnoreCase("isnotnull")) {
                where += propertyNames[i] + " is not null ";
            } else if (operators != null && operators[i].equalsIgnoreCase("isempty")) {
                where += propertyNames[i] + " = '' ";
            } else if (operators != null && operators[i].equalsIgnoreCase("isnotempty")) {
                where += propertyNames[i] + " <> '' ";
            } else if (operators != null && operators[i].equalsIgnoreCase("in")) {
                where += propertyNames[i] + " in ";
            } else {
                where += propertyNames[i]
                        + (operators == null || operators[i] == null ? "=" : " " + operators[i]) + " ? ";
            }
        }

        fullSql = hql + where;
        fullSql += otherCause == null || otherCause.trim().equals("") ? "" : " " + otherCause;

        fullSql += groupBy == null || groupBy.trim().equals("") ? "" : " group by " + groupBy;
        fullSql += orderBy == null || orderBy.trim().equals("") ? "" : " order by " + orderBy;

        query = isCache ? this.createQuery(fullSql).setCacheable(true) : this.createQuery(fullSql);

        int paramIndex = 0;
        for (int i = 0; i <= values.length - 1; i++) {
            if (operators != null && operators[i].equalsIgnoreCase("isnull"))
                continue;
            if (operators != null && operators[i].equalsIgnoreCase("isnotnull"))
                continue;
            if (operators != null && operators[i].equalsIgnoreCase("isempty"))
                continue;
            if (operators != null && operators[i].equalsIgnoreCase("isnotempty"))
                continue;
            // IN?
            if (operators != null && operators[i].equalsIgnoreCase("in")) {
                values[i] = StringUtil.getInString(values[i]);
            }
            query.setParameter(paramIndex++, values[i]);
        }

    } else {
        if ("".equals(where) && hql.indexOf("where") == -1) {
            where = " where 1=1 ";
        } else if (!"".equals(where)) {
            where += " and ";
        }

        fullSql = hql + where;
        fullSql += otherCause == null || otherCause.trim().equals("") ? "" : " " + otherCause;

        fullSql += groupBy == null || groupBy.trim().equals("") ? "" : " group by " + groupBy;
        fullSql += orderBy == null || orderBy.trim().equals("") ? "" : " order by " + orderBy;

        query = this.createQuery(fullSql);
    }

    // ?
    if (isTotalSize) {

        // ???order by ???
        countSql = hql + where;

        // modi by hongdj

        countSql += groupBy == null || groupBy.trim().equals("") ? "" : " group by " + groupBy;
        countSql += otherCause == null || otherCause.trim().equals("") ? "" : " " + otherCause;

        // ?hql?hql??select????
        // select a,b,(select c from table1) as d from table2 ...
        countSql = "select count(*) from " + countSql.substring(countSql.toLowerCase().indexOf("from") + 5);
        Query query2 = this.createQuery(countSql);

        int paramIndex = 0;
        if (values != null) {
            for (int i = 0; i <= values.length - 1; i++) {
                if (operators != null && operators[i].equalsIgnoreCase("isnull"))
                    continue;
                if (operators != null && operators[i].equalsIgnoreCase("isnotnull"))
                    continue;
                if (operators != null && operators[i].equalsIgnoreCase("isempty"))
                    continue;
                if (operators != null && operators[i].equalsIgnoreCase("isnotempty"))
                    continue;
                query2.setParameter(paramIndex++, values[i]);
            }
        }
        // modi by denny
        Long res = (Long) query2.uniqueResult();
        if (res != null) {
            count = res.intValue();
        }
    }

    if (offset > 0) {
        query.setFirstResult(offset);
    }

    if (size > 0) {
        query.setMaxResults(size);
    }

    // ?log
    // logger.debug("fullSql=" + query.getQueryString());

    map.put("list", query.list());
    map.put("count", count);
    return new Object[] { map.get("list"), map.get("count") };
}

From source file:ch.tatool.app.service.impl.TrialDAO.java

License:Open Source License

/** Get all trials for a given session. */
@SuppressWarnings("unchecked")
public List<Trial> getTrials(final ModuleImpl module, final ModuleSession moduleSession,
        final String elementNameLike, final String propertyNameLike, final int offset, final int maxResults) {
    if (elementNameLike == null && propertyNameLike == null) {
        throw new RuntimeException("Either elementName or propertyName needs to be non-null");
    }//ww  w.j  a  v  a2  s .  co m
    return (List<Trial>) getHibernateTemplate().execute(new HibernateCallback() {
        public Object doInHibernate(Session session) {

            getHibernateTemplate().update(module);
            if (moduleSession != null) {
                getHibernateTemplate().update(moduleSession);
            }

            StringBuilder q = new StringBuilder();
            q.append("select distinct(trial) from TrialImpl trial ");
            q.append(" join trial.entriesImpl as entry where ");
            if (moduleSession != null) {
                q.append(" trial.session = :session ");
            } else {
                q.append(" trial.session.module = :module ");
            }
            if (elementNameLike != null) {
                q.append(" and entry.nodeId like :elementName");
            }
            if (propertyNameLike != null) {
                q.append(" and entry.name like :propName");
            }

            // sort reverse
            q.append(" order by trial.id DESC");

            // create the query and set the various parameters
            Query query = session.createQuery(q.toString());
            if (moduleSession != null) {
                query.setParameter("session", moduleSession);
            } else {
                query.setParameter("module", module);
            }
            if (elementNameLike != null) {
                query.setParameter("elementName", elementNameLike);
            }
            if (propertyNameLike != null) {
                query.setParameter("propName", propertyNameLike);
            }
            // limit results if requested
            if (offset > 0) {
                query.setFirstResult(offset);
            }
            if (maxResults > -1) {
                query.setMaxResults(maxResults);
            }
            List<Trial> trials = (List<Trial>) query.list();

            // make sure we set the moduleSession correctly
            if (moduleSession != null) {
                for (Trial t : trials) {
                    t.setSession(moduleSession);
                }
            }

            return trials;
        }
    });
}

From source file:classe.restaurantUtil.java

    cents() {
    List<Restaurant> listeResto = null;
        // w w  w  .  j  a v a  2  s.c  o m
    Transaction tx = null;
    this.session = HibernateUtil.getSessionFactory().openSession();
       
    try {
            
        tx = session.beginTransaction();
            
        Query requete = session.createQuery("FROM Restaurant ORDER BY Idresto DESC");
        requete.setFirstResult(0);
        requete.setMaxResults(3);
           
        listeResto = requete.list();
           
    } catch (Exception e) {
        e.printStackTrace();
    }
       
    this.session.close();
    return listeResto;
}

From source file:cn.dao.MedicineInfoDao.java

@SuppressWarnings("unchecked")
public List<MedicineInfo> query(MedicineInfo vo, PageResult page) {
    Session session = this.getSessionFactory().getCurrentSession();
    Map<String, Object> properties = new HashMap<>();
    StringBuffer hql = new StringBuffer();
    hql.append("from MedicineInfo");
    hql.append(" where 1=1");
    if (vo.getMedicineName() != null && !"".equals(vo.getMedicineName())) {
        hql.append(" and medicineName like :medicineName");
        properties.put("medicineName", "%" + vo.getMedicineName() + "%");
    }//from   w w  w.j  av a2  s . c o  m
    int items = getPageCount(session, hql.toString(), properties);
    page.setItems(items);
    Query query = session.createQuery(hql.toString());
    query.setProperties(properties);
    if (page != null) {
        query.setFirstResult(page.getFirstResult());
        query.setMaxResults(page.getMaxResult());
    }
    return query.list();
}

From source file:cn.dao.MedicinePurchaseDao.java

@SuppressWarnings("unchecked")
public List<Object> query(MedicinePurchase vo, PageResult page) {
    Session session = this.getSessionFactory().getCurrentSession();
    Map<String, Object> properties = new HashMap<>();
    StringBuffer hql = new StringBuffer();
    hql.append("select t.batch_number,t.purchase_date,u.name");
    hql.append(" from medicine_purchase t");
    hql.append(" left join user_info u");
    hql.append(" on t.user_id = u.id");
    hql.append(" group by t.batch_number,t.purchase_date,u.name");
    hql.append(" order by t.purchase_date desc");
    Query query = session.createSQLQuery(hql.toString());
    query.setProperties(properties);/*  w ww  .  jav  a  2  s. c  o m*/
    if (page != null) {
        int items = getPageCount(session, hql.toString(), properties);
        page.setItems(items);
        query.setFirstResult(page.getFirstResult());
        query.setMaxResults(page.getMaxResult());
    }
    return query.list();
}