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

The following examples show how to use javax.persistence.TypedQuery#setFirstResult() . 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: MoviesBean.java    From tomee with Apache License 2.0 6 votes vote down vote up
@Override
public List<Movie> findRange(String field, String searchTerm, int firstResult, int maxResults) {
    CriteriaBuilder qb = entityManager.getCriteriaBuilder();
    CriteriaQuery<Movie> cq = qb.createQuery(Movie.class);
    Root<Movie> root = cq.from(Movie.class);
    EntityType<Movie> type = entityManager.getMetamodel().entity(Movie.class);

    Path<String> path = root.get(type.getDeclaredSingularAttribute(field, String.class));
    Predicate condition = qb.like(path, "%" + searchTerm + "%");

    cq.where(condition);
    TypedQuery<Movie> q = entityManager.createQuery(cq);
    q.setMaxResults(maxResults);
    q.setFirstResult(firstResult);
    return q.getResultList();
}
 
Example 2
Source File: SectionAllocationEndpoint.java    From monolith with Apache License 2.0 6 votes vote down vote up
@GET
@Produces("application/json")
public List<SectionAllocationDTO> listAll(@QueryParam("start") Integer startPosition, @QueryParam("max") Integer maxResult)
{
   TypedQuery<SectionAllocation> findAllQuery = em.createQuery("SELECT DISTINCT s FROM SectionAllocation s LEFT JOIN FETCH s.performance LEFT JOIN FETCH s.section ORDER BY s.id", SectionAllocation.class);
   if (startPosition != null)
   {
      findAllQuery.setFirstResult(startPosition);
   }
   if (maxResult != null)
   {
      findAllQuery.setMaxResults(maxResult);
   }
   final List<SectionAllocation> searchResults = findAllQuery.getResultList();
   final List<SectionAllocationDTO> results = new ArrayList<SectionAllocationDTO>();
   for (SectionAllocation searchResult : searchResults)
   {
      SectionAllocationDTO dto = new SectionAllocationDTO(searchResult);
      results.add(dto);
   }
   return results;
}
 
Example 3
Source File: JpaUserProvider.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public List<UserModel> getUsers(RealmModel realm, int firstResult, int maxResults, boolean includeServiceAccounts) {
    String queryName = includeServiceAccounts ? "getAllUsersByRealm" : "getAllUsersByRealmExcludeServiceAccount" ;

    TypedQuery<UserEntity> query = em.createNamedQuery(queryName, UserEntity.class);
    query.setParameter("realmId", realm.getId());
    if (firstResult != -1) {
        query.setFirstResult(firstResult);
    }
    if (maxResults != -1) {
        query.setMaxResults(maxResults);
    }
    List<UserEntity> results = query.getResultList();
    List<UserModel> users = new LinkedList<>();
    for (UserEntity entity : results) users.add(new UserAdapter(session, realm, em, entity));
    return users;
}
 
Example 4
Source File: QueryImpl.java    From jweb-cms with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public List<T> find() {
    EntityManager em = database.em();
    try {
        TypedQuery<T> query = em.createQuery(sql.selectSQL(), entityClass);
        for (int i = 0; i < params.size(); i++) {
            query.setParameter(i, params.get(i));
        }
        if (page != null) {
            query.setFirstResult((page - 1) * limit);
            query.setMaxResults(limit);
        }
        return query.getResultList();
    } finally {
        em.close();
    }
}
 
Example 5
Source File: MediaItemEndpoint.java    From monolith with Apache License 2.0 6 votes vote down vote up
@GET
@Produces("application/json")
public List<MediaItemDTO> listAll(@QueryParam("start") Integer startPosition, @QueryParam("max") Integer maxResult)
{
   TypedQuery<MediaItem> findAllQuery = em.createQuery("SELECT DISTINCT m FROM MediaItem m ORDER BY m.id", MediaItem.class);
   if (startPosition != null)
   {
      findAllQuery.setFirstResult(startPosition);
   }
   if (maxResult != null)
   {
      findAllQuery.setMaxResults(maxResult);
   }
   final List<MediaItem> searchResults = findAllQuery.getResultList();
   final List<MediaItemDTO> results = new ArrayList<MediaItemDTO>();
   for (MediaItem searchResult : searchResults)
   {
      MediaItemDTO dto = new MediaItemDTO(searchResult);
      results.add(dto);
   }
   return results;
}
 
Example 6
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 7
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 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: JpaUserFederatedStorageProvider.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public List<String> getMembership(RealmModel realm, GroupModel group, int firstResult, int max) {
    TypedQuery<String> query = em.createNamedQuery("fedgroupMembership", String.class)
            .setParameter("realmId", realm.getId())
            .setParameter("groupId", group.getId());
    query.setFirstResult(firstResult);
    query.setMaxResults(max);
    return query.getResultList();
}
 
Example 10
Source File: FooPaginationPersistenceIntegrationTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public final void givenEntitiesExist_whenRetrievingPageViaCriteria_thenCorrect() {
    final int pageSize = 10;
    final CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    final CriteriaQuery<Foo> criteriaQuery = criteriaBuilder.createQuery(Foo.class);
    final Root<Foo> from = criteriaQuery.from(Foo.class);
    final CriteriaQuery<Foo> select = criteriaQuery.select(from);
    final TypedQuery<Foo> typedQuery = entityManager.createQuery(select);
    typedQuery.setFirstResult(0);
    typedQuery.setMaxResults(pageSize);
    final List<Foo> fooList = typedQuery.getResultList();

    // Then
    assertThat(fooList, hasSize(pageSize));
}
 
Example 11
Source File: DDBManagerBean.java    From ipst with Mozilla Public License 2.0 5 votes vote down vote up
public List<ConnectionSchema> findConnectionSchemasAllMaxResults(int firstResult, int maxResult) {
    Principal cPrincipal = getCallerPrincipal();
    TypedQuery<ConnectionSchema> query = em.createQuery("SELECT c FROM ConnectionSchema c order by c.id", ConnectionSchema.class);
    query.setFirstResult(firstResult);
    query.setMaxResults(maxResult);
    return query.getResultList();
}
 
Example 12
Source File: HibernateGenericStore.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Get executable TypedQuery from JpaQueryParameter.
 *
 * @return executable TypedQuery
 */
protected final TypedQuery<T> getTypedQuery( CriteriaBuilder builder, JpaQueryParameters<T> parameters )
{
    List<Function<Root<T>, Predicate>> predicateProviders = parameters.getPredicates();
    List<Function<Root<T>, Order>> orderProviders = parameters.getOrders();
    preProcessPredicates( builder, predicateProviders );

    CriteriaQuery<T> query = builder.createQuery( getClazz() );
    Root<T> root = query.from( getClazz() );
    query.select( root );

    if ( !predicateProviders.isEmpty() )
    {
        List<Predicate> predicates = predicateProviders.stream().map( t -> t.apply( root ) ).collect( Collectors.toList() );
        query.where( predicates.toArray( new Predicate[0] ) );
    }

    if ( !orderProviders.isEmpty() )
    {
        List<Order> orders = orderProviders.stream().map( o -> o.apply( root ) ).collect( Collectors.toList() );
        query.orderBy( orders );
    }

    TypedQuery<T> typedQuery = getExecutableTypedQuery( query );

    if ( parameters.hasFirstResult() )
    {
        typedQuery.setFirstResult( parameters.getFirstResult() );
    }

    if ( parameters.hasMaxResult() )
    {
        typedQuery.setMaxResults( parameters.getMaxResults() );
    }

    return typedQuery
        .setHint( QueryHints.CACHEABLE, parameters.isCacheable( cacheable ) );
}
 
Example 13
Source File: MoviesImpl.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Override
public List<Movie> findRange(final int[] range) {
    final CriteriaQuery<Movie> cq = entityManager.getCriteriaBuilder().createQuery(Movie.class);
    cq.select(cq.from(Movie.class));
    final TypedQuery<Movie> q = entityManager.createQuery(cq);
    q.setMaxResults(range[1] - range[0]);
    q.setFirstResult(range[0]);
    return q.getResultList();
}
 
Example 14
Source File: NoCountPagingRepository.java    From hawkbit with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected Page<T> readPage(final TypedQuery<T> query, final Pageable pageable, final Specification<T> spec) {
    query.setFirstResult((int) pageable.getOffset());
    query.setMaxResults(pageable.getPageSize());

    final List<T> content = query.getResultList();

    return new PageImpl<>(content, pageable, content.size());
}
 
Example 15
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 16
Source File: SimpleBaseRepository.java    From es with Apache License 2.0 5 votes vote down vote up
/**
 * Reads the given {@link javax.persistence.TypedQuery} into a {@link org.springframework.data.domain.Page} applying the given {@link org.springframework.data.domain.Pageable} and
 * {@link org.springframework.data.jpa.domain.Specification}.
 *
 * @param query    must not be {@literal null}.
 * @param spec     can be {@literal null}.
 * @param pageable can be {@literal null}.
 * @return
 */
private Page<M> readPage(TypedQuery<M> query, Pageable pageable, Specification<M> spec) {

    query.setFirstResult(pageable.getOffset());
    query.setMaxResults(pageable.getPageSize());

    Long total = QueryUtils.executeCountQuery(getCountQuery(spec));
    List<M> content = total > pageable.getOffset() ? query.getResultList() : Collections.<M>emptyList();

    return new PageImpl<M>(content, pageable, total);
}
 
Example 17
Source File: SMPPrimaryStorageFactory.java    From zstack with Apache License 2.0 5 votes vote down vote up
@Transactional
public List<HostInventory> getConnectedHostForOperation(PrimaryStorageInventory pri, int startPage, int pageLimit) {
    if (pri.getAttachedClusterUuids().isEmpty()) {
        throw new OperationFailureException(operr("cannot find a Connected host to execute command for smp primary storage[uuid:%s]", pri.getUuid()));
    }

    String sql = "select h from HostVO h " +
            "where h.status = :connectionState and h.clusterUuid in (:clusterUuids) " +
            "and h.uuid not in (select ref.hostUuid from PrimaryStorageHostRefVO ref " +
            "where ref.primaryStorageUuid = :psUuid and ref.hostUuid = h.uuid and ref.status = :status)";
    TypedQuery<HostVO> q = dbf.getEntityManager().createQuery(sql, HostVO.class);
    q.setParameter("connectionState", HostStatus.Connected);
    q.setParameter("clusterUuids", pri.getAttachedClusterUuids());
    q.setParameter("psUuid", pri.getUuid());
    q.setParameter("status", PrimaryStorageHostStatus.Disconnected);

    q.setFirstResult(startPage * pageLimit);
    if (pageLimit > 0){
        q.setMaxResults(pageLimit);
    }

    List<HostVO> ret = q.getResultList();
    if (ret.isEmpty() && startPage == 0) { //check is first page
        throw new OperationFailureException(operr(
                "cannot find a host which has Connected host-SMP connection to execute command for smp primary storage[uuid:%s]",
                pri.getUuid()));
    } else {
        Collections.shuffle(ret);
        return HostInventory.valueOf(ret);
    }
}
 
Example 18
Source File: PageQueryTemplate.java    From mPaaS with Apache License 2.0 5 votes vote down vote up
/**
 * 执行查询
 */
private <T> List<T> executeQuery(QueryRequest request,
		CriteriaQuery<T> query) {
	TypedQuery<T> typedQuery = createQuery(query);
	typedQuery.setFirstResult(request.getOffset());
	typedQuery.setMaxResults(request.getPageSize());
	return typedQuery.getResultList();
}
 
Example 19
Source File: HarvestReportRepositoryImpl.java    From retro-game with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public List<HarvestReport> findReports(User user, HarvestReportSortOrder order, Sort.Direction direction,
                                       Pageable pageable) {
  CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
  CriteriaQuery<HarvestReport> criteriaQuery = criteriaBuilder.createQuery(HarvestReport.class);
  Root<HarvestReport> root = criteriaQuery.from(HarvestReport.class);

  criteriaQuery.where(criteriaBuilder.and(
      criteriaBuilder.equal(root.get("user"), user),
      criteriaBuilder.equal(root.get("deleted"), false)));

  Function<Expression<?>, Order> dirFunc =
      direction == Sort.Direction.ASC ? criteriaBuilder::asc : criteriaBuilder::desc;
  switch (order) {
    case AT: {
      criteriaQuery.orderBy(dirFunc.apply(root.get("at")));
      break;
    }
    case COORDINATES: {
      // galaxy, system, position, kind
      criteriaQuery.orderBy(
          dirFunc.apply(root.get("coordinates").get("galaxy")),
          dirFunc.apply(root.get("coordinates").get("system")),
          dirFunc.apply(root.get("coordinates").get("position")),
          dirFunc.apply(root.get("coordinates").get("kind")));
      break;
    }
    case NUM_RECYCLERS: {
      criteriaQuery.orderBy(dirFunc.apply(root.get("numRecyclers")));
      break;
    }
    case CAPACITY: {
      criteriaQuery.orderBy(dirFunc.apply(root.get("capacity")));
      break;
    }
    case HARVESTED_RESOURCES: {
      criteriaQuery.orderBy(dirFunc.apply(
          criteriaBuilder.sum(root.get("harvestedMetal"), root.get("harvestedCrystal"))));
      break;
    }
    case REMAINING_RESOURCES: {
      criteriaQuery.orderBy(dirFunc.apply(
          criteriaBuilder.sum(root.get("remainingMetal"), root.get("remainingCrystal"))));
      break;
    }
  }

  TypedQuery<HarvestReport> typedQuery = entityManager.createQuery(criteriaQuery);
  typedQuery.setFirstResult((int) pageable.getOffset());
  typedQuery.setMaxResults(pageable.getPageSize());

  return typedQuery.getResultList();
}
 
Example 20
Source File: SurveyEntryDAOImpl.java    From JDeSurvey with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public SortedSet<SurveyEntry> getAll(Long surveyDefinitionId, Integer firstResult, Integer maxResults) {
	
	

	
	
	
	String queryStr =
			"select new com.jd.survey.domain.survey.SurveyEntry(s.id,sd.id,s.ipAddress,d.name,sd.name,s.login, s.firstName,s.middleName,s.lastName,s.email,s.creationDate,s.lastUpdateDate,s.submissionDate,s.status) " +  
			"from Survey s, SurveyDefinition sd, Department d " +
			"where s.typeId=sd.id " +
			"and sd.department.id = d.id " + 
			"and s.typeId = ? order by s.creationDate desc" ; 
	TypedQuery<SurveyEntry> query =   entityManager.createQuery(queryStr, SurveyEntry.class);
	query.setParameter(1, surveyDefinitionId);
	query.setFirstResult(firstResult == null || firstResult < 0 ? DEFAULT_FIRST_RESULT_INDEX : firstResult);
	query.setMaxResults(maxResults == null || maxResults < 0 ? MAX_RESULTS : maxResults);
	
	
	return new TreeSet<SurveyEntry>(query.getResultList());
}