Example usage for org.hibernate.query Query setMaxResults

List of usage examples for org.hibernate.query Query setMaxResults

Introduction

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

Prototype

@Override
    Query<R> setMaxResults(int maxResult);

Source Link

Usage

From source file:be.shad.tsqb.dao.TypeSafeQueryDaoImpl.java

License:Apache License

/**
 * {@inheritDoc}//from   w  w  w. jav  a2 s . co  m
 */
@Override
public <T> QueryResult<T> doQuery(TypeSafeRootQuery tsqbQuery, HibernateQueryConfigurer configurer) {
    HqlQuery hqlQuery = tsqbQuery.toHqlQuery();

    Session currentSession = sessionFactory.getCurrentSession();
    Query<Object[]> query = currentSession.createQuery(hqlQuery.getHql(), Object[].class);
    int position = 0;
    CollectionNamedParameter chunkedParam = null;
    for (Object param : hqlQuery.getParams()) {
        if (param instanceof NamedParameter) {
            NamedParameter named = (NamedParameter) param;
            if (isChunkedParam(named)) {
                if (chunkedParam != null) {
                    throw new IllegalStateException(
                            String.format("More than one batched param [%s, %s] was used in query [%s].",
                                    chunkedParam.getName(), named.getName(), query.getQueryString()));
                }
                // remember batched param to bind iterate and bind chunks later:
                chunkedParam = (CollectionNamedParameter) named;
            } else if (named.getValue() instanceof Collection) {
                query.setParameterList(named.getName(), (Collection<?>) named.getValue());
            } else {
                query.setParameter(named.getName(), named.getValue());
            }
        } else {
            query.setParameter(position++, param);
        }
    }
    if (tsqbQuery.getFirstResult() >= 0) {
        query.setFirstResult(tsqbQuery.getFirstResult());
    }
    if (tsqbQuery.getMaxResults() > 0) {
        query.setMaxResults(tsqbQuery.getMaxResults());
    }

    List<T> results = null;
    if (configurer != null) {
        configurer.beforeQuery(currentSession);
        configurer.configureQuery(query);
        try {
            results = listAll(query, hqlQuery, chunkedParam);
        } finally {
            configurer.afterQuery(currentSession);
        }
    } else {
        results = listAll(query, hqlQuery, chunkedParam);
    }
    return new QueryResult<>(results);
}

From source file:com.pfm.personalfinancemanagergrid.mainClasses.DataGridDataManager.java

private Query buildQuery(Session session, GridParamObject params, boolean maxResults)
        throws ParseException, InstantiationException, IllegalAccessException {
    String source = cache.getEntity();
    List<ColumnRequestObject> columns = params.getColumns();
    String order = source.charAt(0) + "."
            + cache.getColumns().get(params.getOrder().get(0).getColumn()).getColumnName() + " "
            + params.getOrder().get(0).getDir();
    String where = this.buildWhereStatement(params, source.charAt(0));
    if (!"".equals(where)) {
        where = "where " + where;
    }// w ww  . j a  va2  s .  co  m
    Integer iterate = 0;
    Query q = session
            .createQuery("From " + source + " " + source.charAt(0) + " " + where + " order by " + order);
    for (GridCacheTableWhereObject whereObj : cache.getWheres()) {
        replaceQueryParameters(q, whereObj.getColumnType(), whereObj.getColumnName(), whereObj.getWhereVal(),
                whereObj.getWhereType(), "w_" + iterate);
        iterate++;
    }
    Integer iter = 0;
    if (iter < params.getColumns().size()) {
        for (ColumnRequestObject column : params.getColumns()) {
            GridCacheColumnObject cachedColumn = cache.getColumns().get(iter);
            if (!cachedColumn.isOptionsColumn() && cachedColumn.isSearchableColumn()) {
                String columnName = cachedColumn.getColumnName();
                String compareType = column.getFilter().getValue();
                String columnType = cachedColumn.getType();
                String searchVal = column.getSearch().getValue();
                replaceQueryParameters(q, columnType, columnName, searchVal, compareType, "s_" + iter);
            }
            iter++;
        }
    }
    if (maxResults) {
        q.setMaxResults(params.getLength());
        q.setFirstResult(params.getStart());
    }
    return q;
}

From source file:com.wso2telco.services.dep.sandbox.dao.hibernate.HibernateProvisioningDAO.java

License:Open Source License

public List<ProvisionAllService> getApplicableProvisionServices(String number, String username, int offset,
        int limit) throws Exception {
    Session session = getSession();/*from  w  w w.j a  v  a 2 s .com*/
    List<ProvisionAllService> applicableServiceList = new ArrayList<ProvisionAllService>();

    try {
        StringBuilder hqlQueryBuilder = new StringBuilder();
        hqlQueryBuilder.append("select pas ");
        hqlQueryBuilder
                .append("from ProvisionAllService pas,ProvisionMSISDNServicesMap pmsm,ManageNumber mn,User u ");
        hqlQueryBuilder.append("where u.userName = :userName ");
        hqlQueryBuilder.append("and u.id = mn.user.id ");
        hqlQueryBuilder.append("and mn.id = pmsm.msisdnId.id ");
        hqlQueryBuilder.append("and pmsm.servicesId.id = pas.id ");
        hqlQueryBuilder.append("and mn.Number = :number ");

        Query query = session.createQuery(hqlQueryBuilder.toString());

        query.setParameter("userName", username);
        query.setParameter("number", number);
        if (offset > 0) {
            query.setFirstResult(offset);
        }

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

        applicableServiceList = (List<ProvisionAllService>) query.getResultList();
    } catch (Exception ex) {
        LOG.error("###PROVISION### Error in getApplicableProvisionServices " + ex);
        throw ex;
    }

    return applicableServiceList;
}

From source file:com.wso2telco.services.dep.sandbox.dao.hibernate.HibernateProvisioningDAO.java

License:Open Source License

public List<ListProvisionedDTO> getActiveProvisionedServices(String msisdn, String username, int offset,
        int limit) throws Exception {
    Session session = getSession();//from w  ww .  j a  va2s.co  m
    List<ListProvisionedDTO> resultSet = null;
    StringBuilder hql = new StringBuilder();

    hql.append(" SELECT");
    hql.append(
            " services.serviceCode AS serviceCode,services.description AS description,prservice.createdDate AS createdDate,services.tag AS tag,services.value AS value");
    hql.append(" FROM");
    hql.append(" ManageNumber AS num,");
    hql.append(" ProvisionMSISDNServicesMap AS map,");
    hql.append(" ProvisionedServices AS prservice,");
    hql.append(" Status AS stat,");
    hql.append(" ProvisionAllService AS services,");
    hql.append(" User AS user");
    hql.append(" WHERE num.Number = :number");
    hql.append(" AND user.userName= :username");
    hql.append(" AND user.id = num.user.id");
    hql.append(" AND user.id = services.user.id");
    hql.append(" AND map.msisdnId.id = num.id");
    hql.append(" AND map.id = prservice.msisdnServiceMap.id");
    hql.append(" AND map.servicesId.id = services.id");
    hql.append(" AND stat.id = prservice.status.id");
    hql.append(" AND stat.code= :status");

    try {
        Query query = session.createQuery(hql.toString());

        query.setParameter("status", ProvisioningStatusCodes.PRV_PROVISION_SUCCESS.toString());
        query.setParameter("number", msisdn);
        query.setParameter("username", username);

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

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

        resultSet = query.setResultTransformer(Transformers.aliasToBean(ListProvisionedDTO.class))
                .getResultList();
    } catch (Exception ex) {
        LOG.error("###PROVISION### Error in getActiveProvisionedServices " + ex);
        throw ex;
    }
    return resultSet;
}

From source file:com.wso2telco.services.dep.sandbox.dao.hibernate.HibernateWalletDAO.java

License:Open Source License

@Override
public List<AttributeValues> getTransactionValue(String endUserId, List<String> attribute, String tableName,
        Integer userId) throws Exception {

    Session session = getSession();/*w  ww. j a va  2  s  .c o  m*/
    List<AttributeValues> resultSet = null;

    StringBuilder hql = new StringBuilder();
    hql.append("SELECT ");
    hql.append("val ");
    hql.append("FROM ");
    hql.append("AttributeValues AS val, ");
    hql.append("APIServiceCalls AS calls, ");
    hql.append("APITypes AS api, ");
    hql.append("AttributeDistribution AS dist, ");
    hql.append("Attributes AS att, ");
    hql.append("ManageNumber AS number ");
    hql.append("WHERE ");
    hql.append("api.id = calls.apiType.id ");
    hql.append("AND calls.apiServiceCallId = dist.serviceCall.apiServiceCallId ");
    hql.append("AND dist.distributionId = val.attributeDistribution.distributionId ");
    hql.append("AND att.attributeId = dist.attribute.attributeId ");
    hql.append("AND api.apiname =:apiName ");
    hql.append("AND val.tobject =:tableName ");
    hql.append("AND number.id = val.ownerdid ");
    hql.append("AND number.Number =:number ");
    hql.append("AND number.user.id =:userId ");
    hql.append("AND att.attributeName IN ( :attributeName)");

    try {
        Query query = session.createQuery(hql.toString());
        query.setParameter("apiName", RequestType.WALLET.toString().toLowerCase());
        query.setParameter("number", endUserId);
        query.setParameter("tableName", tableName);
        query.setParameterList("attributeName", attribute);
        query.setParameter("userId", userId);
        query.setFirstResult(0);
        query.setMaxResults(20);
        resultSet = (List<AttributeValues>) query.getResultList();

    } catch (NoResultException e) {
        return null;
    } catch (Exception ex) {
        LOG.error("###WALLET### Error in getListTransaction Service ", ex);
        throw ex;
    }
    return resultSet;
}

From source file:dk.fambagge.recipes.db.Database.java

public static <T extends DomainObject> Set<T> queryAll(String hql, Class<T> type, int firstResult,
        int maxResults) {
    final Set<T> namedResult = new LinkedHashSet<>();

    execute((session) -> {/*w  ww .j  a  v  a 2s .c  o m*/
        Query query = session.createQuery(hql);
        if (firstResult != -1) {
            query.setFirstResult(firstResult);
        }

        if (maxResults != -1) {
            query.setMaxResults(maxResults);
        }

        query.setCacheable(true);

        for (Object resultObj : query.list()) {
            namedResult.add((T) resultObj);
        }
    });

    return namedResult;
}

From source file:dk.fambagge.recipes.web.data.LazyCustomList.java

@SuppressWarnings("Duplicates")
@Override/*from   w w  w  . j av a2 s  . c o m*/
public List<T> load(int first, int pageSize, String sortField, SortOrder sortOrder,
        Map<String, Object> filters) {

    List<T> results = new ArrayList<>();

    filterMap = new HashMap<>();

    if (filters != null) {
        filterMap.putAll(filters);
    }

    if (customFilter != null) {
        filterMap.put("name", customFilter);
    }

    Database.execute((session) -> {
        CriteriaBuilder builder = session.getCriteriaBuilder();

        CriteriaQuery<Long> criteriaCount = builder.createQuery(Long.class);
        Root<T> rootCount = criteriaCount.from(domainClass);

        Predicate[] predicatesCount = new Predicate[filterMap.size()];

        //Setup filters
        int i = 0;
        for (Entry<String, Object> entry : filterMap.entrySet()) {
            String filterField = entry.getKey();
            String filterValue = entry.getValue().toString();

            predicatesCount[i] = builder.like(builder.lower(rootCount.get(filterField)),
                    "%" + filterValue.toLowerCase() + "%");
            i++;
        }

        criteriaCount.select(builder.count(rootCount));
        criteriaCount.where(predicatesCount);

        int count = session.createQuery(criteriaCount).uniqueResult().intValue();

        this.setRowCount(count);

        CriteriaQuery<T> criteria = builder.createQuery(domainClass);
        Root<T> root = criteria.from(domainClass);

        Predicate[] predicates = new Predicate[filterMap.size()];

        //Setup filters
        i = 0;
        for (Entry<String, Object> entry : filterMap.entrySet()) {
            String filterField = entry.getKey();
            String filterValue = entry.getValue().toString();

            predicates[i] = builder.like(builder.lower(root.get(filterField)),
                    "%" + filterValue.toLowerCase() + "%");
            i++;
        }

        criteria.select(root);
        criteria.where(predicates);

        String sortFieldFixed = sortField == null ? "name" : sortField;
        SortOrder sortOrderFixed = sortOrder == null ? SortOrder.ASCENDING : sortOrder;

        switch (sortOrderFixed) {
        case ASCENDING:
            criteria.orderBy(builder.asc(root.get(sortFieldFixed)));
            break;
        case DESCENDING:
            criteria.orderBy(builder.desc(root.get(sortFieldFixed)));
            break;
        }

        Query<T> query = session.createQuery(criteria);
        query.setFirstResult(first);
        query.setMaxResults(pageSize);

        results.addAll(query.getResultList());
    });

    return results;
}

From source file:gov.ca.cwds.data.legacy.cms.dao.ClientDao.java

private Client findSingleFacility(String queryName, Consumer<Query<Client>> setParameters) {
    Session session = grabSession();/*from ww  w.  j  a  va 2s .  c o m*/
    Class<Client> entityClass = getEntityClass();
    Query<Client> query = session.createNamedQuery(entityClass.getSimpleName() + "." + queryName, entityClass);
    setParameters.accept(query);
    query.setMaxResults(1);
    Client client = null;
    try {
        client = query.getSingleResult();
    } catch (NoResultException e) {
        LOG.debug(e.getMessage(), e);
    }

    return client;
}

From source file:hu.vitamas.enotesz.dao.EventsDao.java

License:Apache License

/**
 * Returns with upcoming events./*  ww w  .  j  a  v a  2s  . c  om*/
 * 
 * @param userID id of current user
 * @return list of events
 */
public List<Events> upcomingEvents(Integer userID) {
    Instant nowInstant = LocalDate.now().atStartOfDay(ZoneId.systemDefault()).toInstant();

    openSession();
    Query<Events> q = getSession()
            .createQuery("FROM Events WHERE dateTo >= :day and user = :user ORDER BY dateFrom", Events.class);
    q.setParameter("day", Date.from(nowInstant), TemporalType.DATE);
    q.setParameter("user", userID);
    q.setMaxResults(8);
    List<Events> result = q.list();
    closeSession();
    return result;
}

From source file:hu.vitamas.enotesz.dao.TasksDao.java

License:Apache License

/**
 * Returns with tasks of user that contains deadline.
 * //from  w  ww  .  j  a v a  2s  . c  o  m
 * @param userID id of current user
 * @return list of tasks
 */
public List<Tasks> deadlineTasks(Integer userID) {
    openSession();
    Query<Tasks> q = getSession().createQuery(
            "FROM Tasks WHERE deadline is not null and tasksGroups.users.userid = :user", Tasks.class);
    q.setParameter("user", userID);
    q.setMaxResults(8);
    List<Tasks> result = q.list();
    closeSession();
    return result;
}