Example usage for javax.persistence Query setMaxResults

List of usage examples for javax.persistence Query setMaxResults

Introduction

In this page you can find the example usage for javax.persistence Query setMaxResults.

Prototype

Query setMaxResults(int maxResult);

Source Link

Document

Set the maximum number of results to retrieve.

Usage

From source file:org.ejbca.core.ejb.ra.UserData.java

/** @return return the query results as a List. */
@SuppressWarnings("unchecked")
public static List<UserData> findAllBatchUsersByStatus(EntityManager entityManager, int status,
        int maximumQueryRowcount) {
    final Query query = entityManager
            .createQuery("SELECT a FROM UserData a WHERE a.status=:status AND (clearPassword IS NOT NULL)");
    query.setParameter("status", status);
    query.setMaxResults(maximumQueryRowcount);
    return query.getResultList();
}

From source file:org.ow2.sirocco.cloudmanager.core.utils.QueryHelper.java

public static <E extends Identifiable> QueryResult<E> getEntityList(final EntityManager em,
        final QueryParamsBuilder params) throws InvalidRequestException {
    StringBuffer whereClauseSB = new StringBuffer();
    if (params.getTenantId() != null) {
        if (!params.isReturnPublicEntities()) {
            whereClauseSB.append(" v.tenant.id=:tenantId ");
        } else {/*from   ww w.j  av  a2  s . c  o m*/
            whereClauseSB.append(
                    "( v.tenant.id=:tenantId OR v.visibility = org.ow2.sirocco.cloudmanager.model.cimi.extension.Visibility.PUBLIC) ");
        }
    }
    if (params.getStateToIgnore() != null) {
        if (whereClauseSB.length() > 0) {
            whereClauseSB.append(" AND ");
        }
        whereClauseSB.append(" v.state<>" + params.getStateToIgnore().getClass().getName() + "."
                + params.getStateToIgnore().name() + " ");
    }
    if (params.isFilterEmbbededTemplate()) {
        if (whereClauseSB.length() > 0) {
            whereClauseSB.append(" AND ");
        }
        whereClauseSB.append(" v.isEmbeddedInSystemTemplate=false ");
    }
    if (params.getFilters() != null) {
        String filterClause;
        try {
            filterClause = QueryHelper.generateFilterClause(params.getFilters(), "v",
                    params.getClazz().getName() + "$State.");
        } catch (ParseException ex) {
            throw new InvalidRequestException("Parsing error in filter expression " + ex.getMessage());
        } catch (TokenMgrError ex) {
            throw new InvalidRequestException(ex.getMessage());
        }
        if (!filterClause.isEmpty()) {
            if (whereClauseSB.length() > 0) {
                whereClauseSB.append(" AND ");
            }
            whereClauseSB.append(filterClause);
        }
    }

    if (params.getMarker() != null) {
        try {
            Resource resourceAtMarker = (Resource) em
                    .createQuery("SELECT r FROM " + params.getEntityType() + " r WHERE uuid=:uuid")
                    .setParameter("uuid", params.getMarker()).getSingleResult();
            if (whereClauseSB.length() > 0) {
                whereClauseSB.append(" AND ");
            }
            whereClauseSB.append(" v.id>" + resourceAtMarker.getId() + " ");
        } catch (NoResultException e) {
            throw new InvalidRequestException("Invalid marker " + params.getMarker());
        }
    }

    String whereClause = whereClauseSB.toString();

    try {
        int count = ((Number) em
                .createQuery("SELECT COUNT(v) FROM " + params.getEntityType() + " v WHERE " + whereClause)
                .setParameter("tenantId", params.getTenantId()).getSingleResult()).intValue();
        Query query = em.createQuery(
                "SELECT v FROM " + params.getEntityType() + " v  WHERE " + whereClause + " ORDER BY v.id DESC")
                .setParameter("tenantId", params.getTenantId());
        if (params.getLimit() != null) {
            query.setMaxResults(params.getLimit());
        } else {
            if (params.getFirst() != null) {
                query.setFirstResult(params.getFirst());
            }
            if (params.getLast() != null) {
                if (params.getFirst() != null) {
                    query.setMaxResults(params.getLast() - params.getFirst() + 1);
                } else {
                    query.setMaxResults(params.getLast() + 1);
                }
            }
        }
        List<E> queryResult = query.getResultList();
        if (params.getAttributes() != null && params.getAttributes().size() != 0) {
            List<E> items = new ArrayList<E>();
            for (E from : queryResult) {
                E resource = (E) params.getClazz().newInstance();
                for (int i = 0; i < params.getAttributes().size(); i++) {
                    try {
                        PropertyUtils.setSimpleProperty(resource, params.getAttributes().get(i),
                                PropertyUtils.getSimpleProperty(from, params.getAttributes().get(i)));
                    } catch (NoSuchMethodException e) {
                        // ignore wrong attribute name
                    }
                }
                resource.setUuid(from.getUuid());
                if (resource instanceof ICloudProviderResource) {
                    ICloudProviderResource fromResource = (ICloudProviderResource) from;
                    ICloudProviderResource toResource = (ICloudProviderResource) resource;
                    toResource.setLocation(fromResource.getLocation());
                    toResource.setProviderAssignedId(fromResource.getProviderAssignedId());
                    toResource.setCloudProviderAccount(fromResource.getCloudProviderAccount());
                } else if (resource instanceof IMultiCloudResource) {
                    IMultiCloudResource fromResource = (IMultiCloudResource) from;
                    IMultiCloudResource toResource = (IMultiCloudResource) resource;
                    toResource.setProviderMappings(fromResource.getProviderMappings());
                }
                items.add(resource);
            }
            return new QueryResult<E>(count, items);
        } else {
            return new QueryResult<E>(count, queryResult);
        }
    } catch (IllegalArgumentException ex) {
        ex.printStackTrace();
        throw new InvalidRequestException(ex.getMessage());
    } catch (InstantiationException ex) {
        ex.printStackTrace();
        throw new InvalidRequestException(ex.getMessage());
    } catch (IllegalAccessException ex) {
        ex.printStackTrace();
        throw new InvalidRequestException(ex.getMessage());
    } catch (InvocationTargetException ex) {
        throw new InvalidRequestException(ex.getMessage());
    }
}

From source file:org.ow2.sirocco.cloudmanager.core.utils.QueryHelper.java

public static <E> QueryResult<E> getCollectionItemList(final EntityManager em, final QueryParamsBuilder params)
        throws InvalidRequestException {
    StringBuffer whereClauseSB = new StringBuffer();
    if (params.getTenantId() != null) {
        whereClauseSB.append(" v.tenant.id=:tenantId ");
    }// w w w .  ja  va 2 s  . c o m
    if (params.getStateToIgnore() != null) {
        if (whereClauseSB.length() > 0) {
            whereClauseSB.append(" AND ");
        }
        whereClauseSB.append(" vv.state<>" + params.getStateToIgnore().getClass().getName() + "."
                + params.getStateToIgnore().name() + " ");
    }
    if (whereClauseSB.length() > 0) {
        whereClauseSB.append(" AND ");
    }
    whereClauseSB.append("v.uuid=:cid ");
    if (params.getFilters() != null) {
        String filterClause;
        try {
            filterClause = QueryHelper.generateFilterClause(params.getFilters(), "vv",
                    params.getClazz().getName() + "$State.");
        } catch (ParseException ex) {
            throw new InvalidRequestException("Parsing error in filter expression " + ex.getMessage());
        } catch (TokenMgrError ex) {
            throw new InvalidRequestException(ex.getMessage());
        }
        if (!filterClause.isEmpty()) {
            if (whereClauseSB.length() > 0) {
                whereClauseSB.append(" AND ");
            }
            whereClauseSB.append(filterClause);
        }
    }

    String whereClause = whereClauseSB.toString();
    String queryExpression = "SELECT COUNT(vv) FROM " + params.getEntityType() + " vv, "
            + params.getContainerType() + " v WHERE vv MEMBER OF v." + params.getContainerAttributeName()
            + " AND " + whereClause;
    try {
        int count = ((Number) em.createQuery(queryExpression).setParameter("cid", params.getContainerId())
                .setParameter("tenantId", params.getTenantId()).getSingleResult()).intValue();
        queryExpression = "SELECT vv FROM " + params.getEntityType() + " vv, " + params.getContainerType()
                + " v WHERE vv MEMBER OF v." + params.getContainerAttributeName() + " AND " + whereClause
                + " ORDER BY vv.id";
        Query query = em.createQuery(queryExpression).setParameter("cid", params.getContainerId())
                .setParameter("tenantId", params.getTenantId());

        if (params.getFirst() != null) {
            query.setFirstResult(params.getFirst());
        }
        if (params.getLast() != null) {
            if (params.getFirst() != null) {
                query.setMaxResults(params.getLast() - params.getFirst() + 1);
            } else {
                query.setMaxResults(params.getLast() + 1);
            }
        }
        List<E> queryResult = query.getResultList();
        if (params.getAttributes() != null && params.getAttributes().size() != 0) {
            List<E> items = new ArrayList<E>();
            for (E from : queryResult) {
                E resource = (E) params.getClazz().newInstance();
                for (int i = 0; i < params.getAttributes().size(); i++) {
                    try {
                        PropertyUtils.setSimpleProperty(resource, params.getAttributes().get(i),
                                PropertyUtils.getSimpleProperty(from, params.getAttributes().get(i)));
                    } catch (NoSuchMethodException e) {
                        // ignore wrong attribute name
                    }
                }
                items.add(resource);
            }
            return new QueryResult<E>(count, items);
        } else {
            return new QueryResult<E>(count, queryResult);
        }
    } catch (IllegalArgumentException ex) {
        ex.printStackTrace();
        throw new InvalidRequestException(ex.getMessage());
    } catch (InstantiationException ex) {
        ex.printStackTrace();
        throw new InvalidRequestException(ex.getMessage());
    } catch (IllegalAccessException ex) {
        ex.printStackTrace();
        throw new InvalidRequestException(ex.getMessage());
    } catch (InvocationTargetException ex) {
        throw new InvalidRequestException(ex.getMessage());
    }
}

From source file:uk.ac.ebi.intact.editor.services.admin.HqlQueryService.java

@Transactional(value = "jamiTransactionManager", readOnly = true, propagation = Propagation.REQUIRED)
public List<? extends IntactPrimaryObject> runQuery(int maxResults, String hqlQuery) {
    maxResults = Math.min(maxResults, MAX_RESULTS);

    hqlQuery = cleanQuery(hqlQuery);/*  w  ww  .  j ava 2  s. c  om*/

    EntityManager em = getIntactDao().getEntityManager();
    Query query = em.createQuery(hqlQuery);
    query.setMaxResults(maxResults);

    return query.getResultList();
}

From source file:uk.ac.ebi.intact.editor.services.admin.HqlQueryService.java

@Transactional(value = "jamiTransactionManager", readOnly = true, propagation = Propagation.REQUIRED)
public <T> List<T[]> runNativeQuery(int maxResults, String sqlQuery) {
    maxResults = Math.min(maxResults, MAX_RESULTS);

    EntityManager em = getIntactDao().getEntityManager();
    Query query = em.createNativeQuery(sqlQuery);
    query.setMaxResults(maxResults);

    return query.getResultList();
}

From source file:springchat.service.MessagesServiceImpl.java

@Override
public List<MessageEntity> getMessages() {
    return eao.withQuery("SELECT e FROM " + MessageEntity.class.getName() + " e",
            new BaseEAO.ExecutableQuery<List<MessageEntity>>() {
                @Override//from  w w w  . j  a v a  2s. com
                @SuppressWarnings("unchecked")
                public List<MessageEntity> execute(Query query) {
                    query.setMaxResults(MESSAGES_LIMIT);
                    return query.getResultList();
                }
            });
}

From source file:myjpa.guest.model.Guests.java

public List<Guest> findAll(int start, int size) {

    Query query = getJpqlQuery();
    query.setFirstResult(start);//from w w  w  .  j av  a  2 s. c o  m
    query.setMaxResults(size);

    return query.getResultList();
}

From source file:ro.alexdutescu.coduribare.service.AbstractFacade.java

public List<T> findRange(int[] range) {
    javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
    cq.select(cq.from(entityClass));/* w  w w.j a v a  2 s.c  om*/
    javax.persistence.Query q = getEntityManager().createQuery(cq);
    q.setMaxResults(range[1] - range[0] + 1);
    q.setFirstResult(range[0]);
    return q.getResultList();
}

From source file:gumga.framework.application.GumgaCrudAndQueryNotOnlyTypedRepositoryImpl.java

@Override
public List getResultList(String hql, Map<String, Object> param, int maxResult) {
    javax.persistence.Query query = entityManager.createQuery(hql);
    query.setMaxResults(maxResult);
    addParam(query, param);//w w  w  . j  a  va 2  s.  co  m
    return query.getResultList();
}

From source file:gumga.framework.application.GumgaCrudAndQueryNotOnlyTypedRepositoryImpl.java

@SuppressWarnings({ "unchecked", "rawtypes" })
@Override//from   w  ww  .  j a  v  a  2  s  . c o m
public <E> E getUniqueResult(String hql, Class<E> type, Map<String, Object> param) {
    javax.persistence.Query query = entityManager.createQuery(hql);
    query.setMaxResults(1);
    addParam(query, param);
    return type.cast(query.getSingleResult());
}