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

The following are Jave code examples for showing how to use setFirstResult() of the javax.persistence.TypedQuery class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: ait-platform   File: AitEjbUserStorageProvider.java   Source Code and License Vote up 6 votes
@Override
public List<UserModel> getUsers(RealmModel realm, int firstResult, int maxResults) {

	TypedQuery<UserEntity> query = em.createNamedQuery("getAllUsers", UserEntity.class);
	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, model, entity));
	return users;
}
 
Example 2
Project: ait-platform   File: AitEjbUserStorageProvider.java   Source Code and License Vote up 6 votes
@Override
public List<UserModel> searchForUser(String search, RealmModel realm, int firstResult, int maxResults) {
	TypedQuery<UserEntity> query = em.createNamedQuery("searchForUser", UserEntity.class);
	query.setParameter("search", "%" + search.toLowerCase() + "%");
	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, model, entity));
	return users;
}
 
Example 3
Project: linq   File: LinqImpl.java   Source Code and License Vote up 6 votes
@Override
public <T> List<T> list(Pageable pageable) {
	if (parent != null) {
		applyPredicateToCriteria(sq);
		return parent.list(pageable);
	}
	if (pageable == null) {
		return list();
	} else {
		Sort sort = pageable.getSort();
		orders.addAll(QueryUtils.toOrders(sort, root, cb));
		applyPredicateToCriteria(criteria);
		TypedQuery<?> query = em.createQuery(criteria);
		
		query.setFirstResult(pageable.getOffset());
		query.setMaxResults(pageable.getPageSize());

		return transform(query, false);
	}
}
 
Example 4
Project: xm-commons   File: PermittedRepository.java   Source Code and License Vote up 5 votes
private <T> Page<T> readPage(TypedQuery<Long> countQuery, TypedQuery<T> query, Pageable pageable) {
    query.setFirstResult(pageable.getOffset());
    query.setMaxResults(pageable.getPageSize());

    return PageableExecutionUtils.getPage(query.getResultList(), pageable,
        () -> executeCountQuery(countQuery));
}
 
Example 5
Project: search-doc   File: DAOGenerico.java   Source Code and License Vote up 5 votes
public List<T> buscarComLimite(int paginaAtual, int tamanhoPagina) {
    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    CriteriaQuery<T> cq = cb.createQuery(entityClass);
    Root<T> root = cq.from(entityClass);
    cq.select(root);
    cq.orderBy(cb.desc(root.get("id")));
    TypedQuery typedQuery = entityManager.createQuery(cq);
    typedQuery.setFirstResult(paginaAtual);
    typedQuery.setMaxResults(tamanhoPagina);
    return typedQuery.getResultList();
}
 
Example 6
Project: Pet-Supply-Store   File: AbstractPersistenceRepository.java   Source Code and License Vote up 5 votes
/**
 * Returns the query result for a query with a start and limit parameter.
 * Negative starts and limits are ignored.
 * @param em The currently open entity manager.
 * @param query The query. Parameters must all be bound.
 * @param start The start index. Negative values are ignored.
 * @param limit The limit. Negative values are ignored.
 * @return The query result.
 */
protected List<P> resultsWithStartAndLimit(EntityManager em, TypedQuery<P> query, int start, int limit) {
	if (start >= 0) {
		query.setFirstResult(start);
    }
	if (limit >= 0) {
		query = query.setMaxResults(limit);
	}
	return query.getResultList();
}
 
Example 7
Project: keycloak_training   File: EjbExampleUserStorageProvider.java   Source Code and License Vote up 5 votes
@Override
public List<UserModel> getUsers(RealmModel realm, int firstResult, int maxResults) {

    TypedQuery<UserEntity> query = em.createNamedQuery("getAllUsers", UserEntity.class);
    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, model, entity));
    return users;
}
 
Example 8
Project: coodoo-listing   File: ListingQuery.java   Source Code and License Vote up 5 votes
public List<T> list(Integer startPosition, Integer limit) {
    TypedQuery<T> typedQuery = entityManager.createQuery(this.getQuery());
    if (startPosition != null) {
        typedQuery.setFirstResult(startPosition);
    }
    if (limit != null) {
        typedQuery.setMaxResults(limit);
    }
    return typedQuery.getResultList();
}
 
Example 9
Project: testing_security_development_enterprise_systems   File: QuizEjb.java   Source Code and License Vote up 5 votes
public List<Quiz> getRandomQuizzes(int n, long categoryId){

        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 chose " + 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;
    }
 
Example 10
Project: testing_security_development_enterprise_systems   File: QuizEjb.java   Source Code and License Vote up 5 votes
public List<Quiz> getRandomQuizzes(int n, long categoryId){

        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;
    }
 
Example 11
Project: CriteriaBuilder   File: CriteriaServiceImpl.java   Source Code and License Vote up 5 votes
@Override
public List<?> search(String entityName, String query, int limit, int pageNumber)
{
	List<T> resultsList = new ArrayList<>();
	
	Class<T> clazz = entityList.get(entityName);
	
	if(clazz == null) throw new RuntimeException("ENTITY.NOT.FOUND");
	
	boolean isValid = query == null ? true : validateQuery(query, clazz);  
	
	if(isValid) {
		
		CriteriaBuilder criteriaBuilder = entitymanager.getCriteriaBuilder();
		CriteriaQuery<T> cq = criteriaBuilder.createQuery(clazz);
		
		Root<T> root = cq.from(clazz);			
		
		if(query!=null) {
			Predicate predicate = populatePredicates(root, query);
			cq.where(predicate);				
		}
		
           cq.select(root);
           TypedQuery<T> q = entitymanager.createQuery(cq);
           q.setFirstResult((pageNumber-1) * limit);
           q.setMaxResults(limit);
           resultsList = q.getResultList();
           System.out.println(resultsList.size());
	} else {
		throw new RuntimeException("Property defined in the query is not valid, doesn't belong to the entity type:"+entityName);
	}
	return resultsList;
}
 
Example 12
Project: linq   File: JpaUtil.java   Source Code and License Vote up 5 votes
@SuppressWarnings("unchecked")
/**
 * 分页条件查询
 * @param cq 条件
 * @param pageable 分页信息
 * @param <T> 领域类(实体类)范型
 * @return 分页结果
 */
public static <T> Page<T> findAll(CriteriaQuery<T> cq, Pageable pageable) {
	Class<T> domainClass = cq.getResultType();
	Root<T> root;
	if (CollectionUtils.isEmpty(cq.getRoots())) {
		root = cq.from(domainClass);
	} else {
		root = (Root<T>) cq.getRoots().iterator().next();
	}
	EntityManager em = getEntityManager(domainClass);
	if (pageable == null) {
		List<T> list = findAll(cq);
		return new PageImpl<T>(list);
	} else {
		Sort sort = pageable.getSort();
		cq.orderBy(QueryUtils.toOrders(sort, root, em.getCriteriaBuilder()));
		TypedQuery<T> query = em.createQuery(cq);
		
		query.setFirstResult(pageable.getOffset());
		query.setMaxResults(pageable.getPageSize());

		Long total = count(cq);
		List<T> content = total > pageable.getOffset() ? query.getResultList() : Collections.<T> emptyList();

		return new PageImpl<T>(content, pageable, total);
	}
}
 
Example 13
Project: linq   File: LinqImpl.java   Source Code and License Vote up 5 votes
@Override
public <T> Page<T> paging(Pageable pageable) {
	if (parent != null) {
		applyPredicateToCriteria(sq);
		return parent.paging(pageable);
	}
	List<T> list;
	if (pageable == null) {
		list = list();
		return new PageImpl<T>(list);
	} else {
		Sort sort = pageable.getSort();
		if (sort != null) {
			orders.addAll(QueryUtils.toOrders(sort, root, cb));
		}
		applyPredicateToCriteria(criteria);
		TypedQuery<?> query = em.createQuery(criteria);
		
		query.setFirstResult(pageable.getOffset());
		query.setMaxResults(pageable.getPageSize());

		Long total = JpaUtil.count(criteria);
		List<T> content = Collections.<T> emptyList();
		if (total > pageable.getOffset()) {
			content = transform(query, false);
		}

		return new PageImpl<T>(content, pageable, total);
	}
}
 
Example 14
Project: linq   File: LinqImpl.java   Source Code and License Vote up 5 votes
@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
Project: strqlbuilder   File: StrQLBuilderNativeTest.java   Source Code and License Vote up 4 votes
@Test
   public void personDTOResultTest() {
StrQLBuilder sql = StrQLBuilder.createNative()
	.select("p.id_person as idPerson")
	.select("p.name AS name")
	.select("p.surname as \"surname\"")
	.select("p.enabled as enabled,p.alive as alive")
	.select("p.creation_date as creationDate")
	.select("p.age as age, p.height as height")
	.select("p.name as reallyLongPropertyToTestLongAliases")
	.select("p.name as \"reallyLongPropertyToTestLongAliases\"")
	.select("p.birthday")
	.select("p.name as parent.name")
	.from("Person p")
	.leftjoin("Job j").on("j.id_job = p.id_job").and("p.name = :name", "Luis")
	.where("p.name = :pname", "Luis")
	.andlike("p.name", ":name_pattern", "uis")
	.and("p.name IN :pnamearray", (Object) new String[] { "Luis" })
	.and("p.name IN :pnamelist", Arrays.asList("Luis"))
	.and("p.name IN (:pnamelist2)", Arrays.asList("Luis"))
	.order(by("surname", DESC).and("name"));

TypedQuery<PersonDTO> query = sql.createQuery(entityManager, PersonDTO.class);
query.setFirstResult(0);
query.setMaxResults(1);
List<PersonDTO> persons = query.getResultList();

assertThat(persons, hasSize(1));
PersonDTO person = persons.get(0);
assertThat(person, is(not(nullValue())));
assertThat(person.getIdPerson(), is(not(nullValue())));
assertThat(person.getName(), is("Luis"));
assertThat(person.getSurname(), is("Labiano"));
assertThat(person.getAge(), is(11));
assertThat(person.getHeight(), is(1.20f));
assertThat(person.getBirthday(), is(not(nullValue())));
assertThat(person.getCreationDate(), is(not(nullValue())));
assertThat(person.getEnabled(), is(Enabled.ENABLED));
assertThat(person.getAlive(), is(true));
assertThat(person.getReallyLongPropertyToTestLongAliases(), is("Luis"));
assertThat(person.getParent().getName(), is("Luis"));
   }
 
Example 16
Project: sucok-framework   File: BaseDao.java   Source Code and License Vote up 4 votes
public List<R> list(int offset, int size) {
	TypedQuery<R> typedQuery = em.createQuery(query);
	typedQuery.setFirstResult(offset);
	typedQuery.setMaxResults(size);
	return typedQuery.getResultList();
}
 
Example 17
Project: strqlbuilder   File: StrQLBuilderJPQLTest.java   Source Code and License Vote up 4 votes
@Test
   public void personDTOResultTest() {
StrQLBuilder jpa = StrQLBuilder.createJPQL()
	.select("p.id as idPerson")
	.select("p.name as name")
	.select("p.surname as \"surname\"")
	.select("p.enabled as enabled, p.alive as alive")
	.select("p.creationDate as creationDate")
	.select("p.age as age, p.height as height")
	.select("p.name as reallyLongPropertyToTestLongAliases")
	.select("p.name as \"reallyLongPropertyToTestLongAliases\"")
	.select("p.birthday")
	.select("p.name as \"parent.name\"")
	.from("Person p")
	.leftjoin("p.job j").with()
	.where("p.name = :pname", "Luis")
	.andlike("p.name", ":name_pattern", "uis")
	.and("p.name IN :pnamearray", (Object) new String[] { "Luis" })
	.and("p.name IN :pnamelist", Arrays.asList("Luis"))
	.and("p.name IN (:pnamelist2)", Arrays.asList("Luis"))
	.order(by("surname", DESC).and("name"));

TypedQuery<PersonDTO> query = jpa.createQuery(entityManager, PersonDTO.class);
query.setFirstResult(0);
query.setMaxResults(1);
List<PersonDTO> persons = query.getResultList();

assertThat(persons, hasSize(1));
PersonDTO person = persons.get(0);
assertThat(person, is(not(nullValue())));
assertThat(person.getIdPerson(), is(not(nullValue())));
assertThat(person.getName(), is("Luis"));
assertThat(person.getSurname(), is("Labiano"));
assertThat(person.getAge(), is(11));
assertThat(person.getHeight(), is(1.20f));
assertThat(person.getBirthday(), is(not(nullValue())));
assertThat(person.getCreationDate(), is(not(nullValue())));
assertThat(person.getEnabled(), is(Enabled.ENABLED));
assertThat(person.getAlive(), is(true));
assertThat(person.getReallyLongPropertyToTestLongAliases(), is("Luis"));
assertThat(person.getParent().getName(), is("Luis"));
   }
 
Example 18
Project: spring-data-examples   File: CustomerServiceImpl.java   Source Code and License Vote up 3 votes
@Override
public List<Customer> findAll(int page, int pageSize) {

	TypedQuery<Customer> query = em.createQuery("select c from Customer c", Customer.class);

	query.setFirstResult(page * pageSize);
	query.setMaxResults(pageSize);

	return query.getResultList();
}
 
Example 19
Project: bootstrap   File: PaginationDao.java   Source Code and License Vote up 3 votes
/**
 * Reads the given {@link TypedQuery} into a {@link Page} applying the given {@link Pageable} and
 * {@link Specification}.
 */
private <T> Page<T> readPage(final Class<T> entityType, final TypedQuery<T> query, final Pageable pageable, final Specification<T> spec) {

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

	final Long total = getCountQuery(entityType, spec).getSingleResult();

	return new PageImpl<>(query.getResultList(), pageable, total);
}
 
Example 20
Project: strqlbuilder   File: StrQLBuilder.java   Source Code and License Vote up 3 votes
/**
 * Create an instance of {@code com.github.iaunzu.strqlbuilder.pagination.PagedTypedQuery<X>} for executing a paged query.
 * 
 * @param entityManager
 *            the {@link javax.persistence.EntityManager} that will manage transaction.
 * @param clazz
 *            the class of the resulting instance(s).
 * @param pageable
 *            an object with pagination info.
 * @return the new query instance
 */
public <X> PagedTypedQuery<X> createPagedQuery(EntityManager entityManager, Class<X> clazz, Pageable pageable)
{
	TypedQuery<X> pageQuery = createQuery(entityManager, clazz, false);
	pageQuery.setFirstResult(pageable.getOffset());
	pageQuery.setMaxResults(pageable.getPageSize());
	TypedQuery<Long> countQuery = createQuery(entityManager, Long.class, true);
	return new PagedTypedQueryImpl<X>(pageQuery, pageable, countQuery);
}