Java Code Examples for javax.persistence.TypedQuery#setMaxResults()

The following examples show how to use javax.persistence.TypedQuery#setMaxResults() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JpaQueryUtils.java    From we-cmdb with Apache License 2.0 7 votes vote down vote up
public static void applyPaging(boolean isPaging, Pageable pageable, TypedQuery typedQuery) {
    if (isPaging && pageable != null) {
        int startIndex = pageable.getStartIndex();
        int pageSize = pageable.getPageSize();
        typedQuery.setFirstResult(startIndex);
        typedQuery.setMaxResults(pageSize);
    }
}
 
Example 2
Source File: BookingEndpoint.java    From monolith with Apache License 2.0 6 votes vote down vote up
@GET
@Produces("application/json")
public List<BookingDTO> listAll(@QueryParam("start") Integer startPosition, @QueryParam("max") Integer maxResult)
{
   TypedQuery<Booking> findAllQuery = em.createQuery("SELECT DISTINCT b FROM Booking b LEFT JOIN FETCH b.tickets LEFT JOIN FETCH b.performance ORDER BY b.id", Booking.class);
   if (startPosition != null)
   {
      findAllQuery.setFirstResult(startPosition);
   }
   if (maxResult != null)
   {
      findAllQuery.setMaxResults(maxResult);
   }
   final List<Booking> searchResults = findAllQuery.getResultList();
   final List<BookingDTO> results = new ArrayList<BookingDTO>();
   for (Booking searchResult : searchResults)
   {
      BookingDTO dto = new BookingDTO(searchResult);
      results.add(dto);
   }
   return results;
}
 
Example 3
Source File: EventCategoryEndpoint.java    From monolith with Apache License 2.0 6 votes vote down vote up
@GET
@Produces("application/json")
public List<EventCategoryDTO> listAll(@QueryParam("start") Integer startPosition, @QueryParam("max") Integer maxResult)
{
   TypedQuery<EventCategory> findAllQuery = em.createQuery("SELECT DISTINCT e FROM EventCategory e ORDER BY e.id", EventCategory.class);
   if (startPosition != null)
   {
      findAllQuery.setFirstResult(startPosition);
   }
   if (maxResult != null)
   {
      findAllQuery.setMaxResults(maxResult);
   }
   final List<EventCategory> searchResults = findAllQuery.getResultList();
   final List<EventCategoryDTO> results = new ArrayList<EventCategoryDTO>();
   for (EventCategory searchResult : searchResults)
   {
      EventCategoryDTO dto = new EventCategoryDTO(searchResult);
      results.add(dto);
   }
   return results;
}
 
Example 4
Source File: PerformanceEndpoint.java    From monolith with Apache License 2.0 6 votes vote down vote up
@GET
@Produces("application/json")
public List<PerformanceDTO> listAll(@QueryParam("start") Integer startPosition, @QueryParam("max") Integer maxResult)
{
   TypedQuery<Performance> findAllQuery = em.createQuery("SELECT DISTINCT p FROM Performance p LEFT JOIN FETCH p.show ORDER BY p.id", Performance.class);
   if (startPosition != null)
   {
      findAllQuery.setFirstResult(startPosition);
   }
   if (maxResult != null)
   {
      findAllQuery.setMaxResults(maxResult);
   }
   final List<Performance> searchResults = findAllQuery.getResultList();
   final List<PerformanceDTO> results = new ArrayList<PerformanceDTO>();
   for (Performance searchResult : searchResults)
   {
      PerformanceDTO dto = new PerformanceDTO(searchResult);
      results.add(dto);
   }
   return results;
}
 
Example 5
Source File: SectionEndpoint.java    From monolith with Apache License 2.0 6 votes vote down vote up
@GET
@Produces("application/json")
public List<SectionDTO> listAll(@QueryParam("start") Integer startPosition, @QueryParam("max") Integer maxResult)
{
   TypedQuery<Section> findAllQuery = em.createQuery("SELECT DISTINCT s FROM Section s LEFT JOIN FETCH s.venue ORDER BY s.id", Section.class);
   if (startPosition != null)
   {
      findAllQuery.setFirstResult(startPosition);
   }
   if (maxResult != null)
   {
      findAllQuery.setMaxResults(maxResult);
   }
   final List<Section> searchResults = findAllQuery.getResultList();
   final List<SectionDTO> results = new ArrayList<SectionDTO>();
   for (Section searchResult : searchResults)
   {
      SectionDTO dto = new SectionDTO(searchResult);
      results.add(dto);
   }
   return results;
}
 
Example 6
Source File: LinqImpl.java    From bdf3 with Apache License 2.0 5 votes vote down vote up
@Override
public <T> List<T> list(int page, int size) {
	if (parent != null) {
		applyPredicateToCriteria(sq);
		return parent.list(page, size);
	}
	applyPredicateToCriteria(criteria);
	TypedQuery<?> query = em.createQuery(criteria);
	
	query.setFirstResult(page*size);
	query.setMaxResults(size);

	return transform(query, false);
}
 
Example 7
Source File: DesignatedHostAllocatorFlow.java    From zstack with Apache License 2.0 5 votes vote down vote up
@Transactional(readOnly = true)
private List<HostVO> allocate(String zoneUuid, String clusterUuid, String hostUuid, String hypervisorType) {
    StringBuilder sql = new StringBuilder();
    sql.append("select h from HostVO h where ");
    if (zoneUuid != null) {
        sql.append(String.format("h.zoneUuid = '%s' and ", zoneUuid));
    }
    if (clusterUuid != null) {
        sql.append(String.format("h.clusterUuid = '%s' and ", clusterUuid));
    }
    if (hostUuid != null) {
        sql.append(String.format("h.uuid = '%s' and ", hostUuid));
    }
    if (hypervisorType != null) {
        sql.append(String.format("h.hypervisorType = '%s' and ", hypervisorType));
    }
    sql.append(String.format("h.status = '%s' and h.state = '%s'", HostStatus.Connected, HostState.Enabled));
    logger.debug("DesignatedHostAllocatorFlow sql: " + sql);
    TypedQuery<HostVO> query = dbf.getEntityManager().createQuery(sql.toString(), HostVO.class);

    if (usePagination()) {
        query.setFirstResult(paginationInfo.getOffset());
        query.setMaxResults(paginationInfo.getLimit());
    }

    return query.getResultList();
}
 
Example 8
Source File: DDBManagerBean.java    From ipst with Mozilla Public License 2.0 5 votes vote down vote up
public List<ParametersContainer> findParametersContainerAllMaxResults(int firstResult, int maxResult) {
    Principal cPrincipal = getCallerPrincipal();
    TypedQuery<ParametersContainer> query = em.createQuery("SELECT m FROM ParametersContainer m order by m.id",
            ParametersContainer.class);
    query.setFirstResult(firstResult);
    query.setMaxResults(maxResult);
    return query.getResultList();
}
 
Example 9
Source File: EmployeeRepository.java    From batchers with Apache License 2.0 5 votes vote down vote up
public List<Employee> getEmployees(int page, int pageSize) {
    TypedQuery<Employee> employees = entityManager.createNamedQuery(Employee.GET_ALL, Employee.class);
    employees.setFirstResult(page * pageSize);
    employees.setMaxResults(pageSize);

    return employees.getResultList();
}
 
Example 10
Source File: UserEJB.java    From testing_security_development_enterprise_systems with GNU Lesser General Public License v3.0 5 votes vote down vote up
public List<User> getTopUsersWithoutCounter(int n) {

        TypedQuery<User> query = em.createQuery(
                "select u from User u order by size(u.posts) + size(u.comments) DESC",
                User.class);
        query.setMaxResults(n);

        return query.getResultList();
    }
 
Example 11
Source File: UserDao.java    From WebApplication-Project-Skeleton with MIT License 5 votes vote down vote up
private User getSingleResultOrNull(TypedQuery<User> query) {
    query.setMaxResults(1);
    List<User> list = query.getResultList();
    if (list.isEmpty()) {
        return null;
    }
    return list.get(0);
}
 
Example 12
Source File: JpaRealmProvider.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public List<ClientModel> searchClientsByClientId(String clientId, Integer firstResult, Integer maxResults, RealmModel realm) {
    TypedQuery<String> query = em.createNamedQuery("searchClientsByClientId", String.class);
    if (firstResult != null && firstResult > 0) {
        query.setFirstResult(firstResult);
    }
    if (maxResults != null && maxResults > 0) {
        query.setMaxResults(maxResults);
    }
    query.setParameter("clientId", clientId);
    query.setParameter("realm", realm.getId());
    List<String> results = query.getResultList();
    if (results.isEmpty()) return Collections.EMPTY_LIST;
    return results.stream().map(id -> session.realms().getClientById(id, realm)).collect(Collectors.toList());
}
 
Example 13
Source File: LinqImpl.java    From bdf3 with Apache License 2.0 5 votes vote down vote up
@Override
public <T> void paging(Page<T> page) {
	if (parent != null) {
		beforeExecute(sq);
		parent.paging(page);
		return;
	}
	List<T> list = Collections.<T> emptyList();
	Long total = 0L;
	if (page == null) {
		list = list();
		total = (long) list.size();
	} else {
		beforeExecute(criteria);
		TypedQuery<?> query = em.createQuery(criteria);
		
		query.setFirstResult((page.getPageNo() - 1)*page.getPageSize());
		query.setMaxResults(page.getPageSize());

		total = JpaUtil.count(criteria);
		if (total > (page.getPageNo() - 1)*page.getPageSize()) {
			list = transform(query, false);
		}
	}
	page.setEntities(list);
	page.setEntityCount(total.intValue());
}
 
Example 14
Source File: LinqImpl.java    From linq with Apache License 2.0 5 votes vote down vote up
@Override
public <T> List<T> list(int page, int size) {
	if (parent != null) {
		applyPredicateToCriteria(sq);
		return parent.list(page, size);
	}
	applyPredicateToCriteria(criteria);
	TypedQuery<?> query = em.createQuery(criteria);
	
	query.setFirstResult(page*size);
	query.setMaxResults(size);

	return transform(query, false);
}
 
Example 15
Source File: NativeJpaQueryTranslator.java    From rice with Educational Community License v2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void convertQueryFlags(QueryByCriteria qbc, TypedQuery query) {
    final int startAtIndex = qbc.getStartAtIndex() != null ? qbc.getStartAtIndex() : 0;

    query.setFirstResult(startAtIndex);

    if (qbc.getMaxResults() != null) {
        //not subtracting one from MaxResults in order to retrieve
        //one extra row so that the MoreResultsAvailable field can be set
        query.setMaxResults(qbc.getMaxResults());
    }
}
 
Example 16
Source File: EntityRepositoryHandler.java    From deltaspike with Apache License 2.0 5 votes vote down vote up
private List<E> executeExampleQuery(E example, int start, int max, boolean useLikeOperator,
                                    SingularAttribute<E, ?>... attributes)
{
    // Not sure if this should be the intended behaviour
    // when we don't get any attributes maybe we should
    // return a empty list instead of all results
    if (isEmpty(attributes))
    {
        return findAll(start, max);
    }

    List<Property<Object>> properties = extractProperties(attributes);
    String jpqlQuery = exampleQuery(allQuery(), properties, useLikeOperator);
    log.log(Level.FINER, "findBy|findByLike: Created query {0}", jpqlQuery);
    TypedQuery<E> query = entityManager().createQuery(jpqlQuery, entityClass());

    // set starting position
    if (start > 0)
    {
        query.setFirstResult(start);
    }

    // set maximum results
    if (max > 0)
    {
        query.setMaxResults(max);
    }

    context.applyRestrictions(query);
    addParameters(query, example, properties, useLikeOperator);
    return query.getResultList();
}
 
Example 17
Source File: DDBManagerBean.java    From ipst with Mozilla Public License 2.0 5 votes vote down vote up
public List<ModelTemplateContainer> findModelTemplateContainerAllMaxResults(int firstResult, int maxResult) {
    Principal cPrincipal = getCallerPrincipal();
    TypedQuery<ModelTemplateContainer> query = em.createQuery("SELECT m FROM ModelTemplateContainer m order by m.id",
            ModelTemplateContainer.class);
    query.setFirstResult(firstResult);
    query.setMaxResults(maxResult);
    return query.getResultList();
}
 
Example 18
Source File: CodelessDaoProxy.java    From sca-best-practice with Apache License 2.0 5 votes vote down vote up
protected <T> Page<T> readPage(final Class<T> clazz, TypedQuery<T> query, Pageable pageable,
                               @Nullable Specification<T> spec) {

    if (pageable.isPaged()) {
        query.setFirstResult((int)pageable.getOffset());
        query.setMaxResults(pageable.getPageSize());
    }

    return PageableExecutionUtils.getPage(query.getResultList(), pageable,
        () -> executeCountQuery(getCountQuery(clazz, spec)));
}
 
Example 19
Source File: TrackerOperationDataService.java    From peer-os with Apache License 2.0 4 votes vote down vote up
public List<TrackerOperationView> getRecentUserOperations( String source, final Date fromDate, final Date toDate,
                                                           int limit, long userId ) throws SQLException
{
    source = source.toUpperCase();
    List<TrackerOperationView> result = Lists.newArrayList();
    EntityManager em = emf.createEntityManager();
    try
    {
        em.getTransaction().begin();

        TypedQuery<String> query = em.createQuery(
                "select to.info from TrackerOperationEntity to where to.source = :source and to.ts >= :fromDate "
                        + "and to.ts <= :toDate and to.userId = :userId order by to.ts desc", String.class );
        query.setParameter( "source", source );
        query.setParameter( "fromDate", fromDate.getTime() );
        query.setParameter( "toDate", toDate.getTime() );
        query.setParameter( "userId", userId );
        query.setMaxResults( limit );
        List<String> infoList = query.getResultList();
        for ( final String info : infoList )
        {
            result.add( createTrackerOperation( info ) );
        }

        em.getTransaction().commit();
    }
    catch ( Exception e )
    {
        LOGGER.error( "Error in getTrackerOperations.", e );
        if ( em.getTransaction().isActive() )
        {
            em.getTransaction().rollback();
        }
        throw new SQLException( e );
    }
    finally
    {
        em.close();
    }
    return result;
}
 
Example 20
Source File: QuizEjb.java    From testing_security_development_enterprise_systems with GNU Lesser General Public License v3.0 4 votes vote down vote up
public List<Quiz> getRandomQuizzes(int n, long categoryId){

        /*
            There can be different ways to sample N rows at random from a table.
            Differences are on performance, based on expected size of the table,
            and the average N values.
            Following approach is "fine" for large tables and low N.

            The idea is that we first make a query to know how many R rows there
            are in the table.
            Then, we make N SQL selects, each one retrieving one row. Rows are
            selected at random, with no replacement.
            When we make a JPQL command, we can specify to get only a subsets of the
            rows, starting at a index K, retrieving Z elements starting from such index K.
            So, here K is at random, and Z=1.
            This process is repeated N times.
            Note that this can end up in 1+N SQL queries. However, it does not require
            any sorting on the table, which would have a O(R*log(R)) complexity.

            However, there is the possibility that a repeated SELECT on same data does not return
            the same ordering (there is no guarantee), unless we explicitly set it with ORDER BY.
            But we could handle the rare case of conflicts (eg 2 different indices resulting by chance in the
            same data because ordering was different) here in the code (which likely would be cheaper
            than forcing a sorting).
         */

        TypedQuery<Long> sizeQuery= em.createQuery(
                "select count(q) from Quiz q where q.subCategory.parent.id=?1", Long.class);
        sizeQuery.setParameter(1, categoryId);
        long size = sizeQuery.getSingleResult();

        if(n > size){
            throw new IllegalArgumentException("Cannot choose " + n + " unique quizzes out of the " + size + " existing");
        }

        Random random = new Random();

        List<Quiz> quizzes = new ArrayList<>();
        Set<Integer> chosen = new HashSet<>();

        while(chosen.size() < n) {

            int k = random.nextInt((int)size);
            if(chosen.contains(k)){
                continue;
            }
            chosen.add(k);

            TypedQuery<Quiz> query = em.createQuery(
                    "select q from Quiz q where q.subCategory.parent.id=?1", Quiz.class);
            query.setParameter(1, categoryId);
            query.setMaxResults(1);
            query.setFirstResult(k);

            quizzes.add(query.getSingleResult());
        }


        return  quizzes;
    }