Java Code Examples for javax.persistence.Query.setMaxResults()

The following are Jave code examples for showing how to use setMaxResults() of the javax.persistence.Query 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: ChronoBike   File: NotificacionesJpaController.java   Source Code and License Vote up 9 votes
public List<Notificaciones> getNotifications(boolean all, int maxResults, int firstResult, String _id) {
    EntityManager em = getEntityManager();
    List<Notificaciones> result = new ArrayList<>();
    try {
        Query q = em.createNativeQuery(String.format(SQL_NOTIFICATION, _id), Notificaciones.class);

        if (!all) {
            q.setMaxResults(maxResults);
            q.setFirstResult(firstResult);
        }
        result = q.getResultList();
        return result;
    } finally {
        em.close();
    }
}
 
Example 2
Project: bdf2   File: JpaDao.java   Source Code and License Vote up 7 votes
@SuppressWarnings("unchecked")
public void pagingQuery(String jpql,String countJpql,Page<?> page,Map<String,Object> parameter,String dataSourceName){
	EntityManager em=this.getEntityManager(dataSourceName);
	Query query=em.createQuery(jpql);
	if(parameter!=null){
		this.setParameter(query, parameter);				
	}
	query.setFirstResult((page.getPageNo()-1)*page.getPageSize());
	query.setMaxResults(page.getPageSize());
	page.setEntities(query.getResultList());
	Query countQuery=em.createQuery(countJpql);
	if(parameter!=null){
		this.setParameter(countQuery, parameter);				
	}
	int count=0;
	Object obj=countQuery.getSingleResult();
	if(obj instanceof Integer){
		count=(Integer)obj;
	}else if(obj instanceof Long){
		count=((Long)obj).intValue();
	}else{
		throw new IllegalArgumentException("The ql["+countJpql+"] fetch result is "+obj+",can not convert to int value");
	}
	page.setEntityCount(count);
}
 
Example 3
Project: marathonv5   File: CumulativeLiveSalesFacadeREST.java   Source Code and License Vote up 6 votes
@GET
@Path("/recent/")
@Produces({"application/xml", "application/json"})
public List<TransitCumulativeSales> findRecent() {     
    Query baseRangeQuery = em.createQuery(BASE_RANGE_QUERY); 
    //Query baseRangeQuery = getEntityManager().createQuery(BASE_RANGE_QUERY);
    baseRangeQuery.setMaxResults(200);
    List<TransitCumulativeSales> result = new ArrayList<TransitCumulativeSales>();
    List<Object[]> resultList = baseRangeQuery.getResultList();
    System.out.print("hello world");
    for (int i=0; i < resultList.size(); i++){
        Object o[] = resultList.get(i);
        TransitCumulativeSales t = new TransitCumulativeSales();
        t.setStartDailySalesId((Integer)o[0]);
        t.setEndDailySalesId((Integer)o[1]);
        t.setCost((Double)o[2]);
        t.setSales((Double) o[3]);
        t.setDate((Date)o[4]);
        result.add(t);
    }
    return result;
}
 
Example 4
Project: ChronoBike   File: UsuarioJpaController.java   Source Code and License Vote up 6 votes
private List<Usuario> findPersonaEntities(boolean all, int maxResults, int firstResult) {
    EntityManager em = getEntityManager();
    try {
        CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
        cq.select(cq.from(Usuario.class));
        Query q = em.createQuery(cq);
        if (!all) {
            q.setMaxResults(maxResults);
            q.setFirstResult(firstResult);
        }
        return q.getResultList();
    } finally {
        em.close();
    }
}
 
Example 5
Project: marathonv5   File: LiveSalesListFacadeREST.java   Source Code and License Vote up 6 votes
@GET
@Produces({"application/xml", "application/json"})
@Path("/recent/producttype/{id}/{orderLineId}")
public List<LiveSalesList> findRecentProductTypeFrom(@PathParam("id") Integer productTypeId, @PathParam("orderLineId") Integer orderLineId) {
    CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
    javax.persistence.criteria.CriteriaQuery cq = cb.createQuery();
    Root<LiveSalesList> liveSalesList = cq.from(LiveSalesList.class);
    cq.select(liveSalesList);
    cq.where(cb.and(
        cb.equal(liveSalesList.get(LiveSalesList_.productTypeId), productTypeId),
        cb.gt(liveSalesList.get(LiveSalesList_.orderLineId), orderLineId)
    ));
    Query q = getEntityManager().createQuery(cq);
    q.setMaxResults(500);
    return q.getResultList();
}
 
Example 6
Project: oscm   File: SharesDataRetrievalServiceBean.java   Source Code and License Vote up 6 votes
@Override
public BigDecimal loadOperatorRevenueSharePercentage(long serviceKey,
        long endPeriod) {
    Query query = dm
            .createNamedQuery("RevenueShareModelHistory.findOperatorRevenueSharePercentage");
    query.setParameter("productObjKey", Long.valueOf(serviceKey));
    query.setParameter("modDate", new Date(endPeriod));
    query.setMaxResults(1);

    BigDecimal percentage;
    try {
        RevenueShareModelHistory revenueShareModelHistory = (RevenueShareModelHistory) query
                .getSingleResult();
        percentage = revenueShareModelHistory.getDataContainer()
                .getRevenueShare();
    } catch (NoResultException e) {
        logger.logError(
                Log4jLogger.SYSTEM_LOG,
                e,
                LogMessageIdentifier.ERROR_OPERATOR_REVENUE_SHARE_OF_SERVICE_NOT_FOUND,
                Long.toString(serviceKey));
        throw e;
    }
    return percentage;
}
 
Example 7
Project: marathonv5   File: CumulativeLiveSalesFacadeREST.java   Source Code and License Vote up 6 votes
@GET
@Path("/recent/")
@Produces({"application/xml", "application/json"})
public List<TransitCumulativeSales> findRecent() {     
    Query baseRangeQuery = em.createQuery(BASE_RANGE_QUERY); 
    //Query baseRangeQuery = getEntityManager().createQuery(BASE_RANGE_QUERY);
    baseRangeQuery.setMaxResults(200);
    List<TransitCumulativeSales> result = new ArrayList<TransitCumulativeSales>();
    List<Object[]> resultList = baseRangeQuery.getResultList();
    System.out.print("hello world");
    for (int i=0; i < resultList.size(); i++){
        Object o[] = resultList.get(i);
        TransitCumulativeSales t = new TransitCumulativeSales();
        t.setStartDailySalesId((Integer)o[0]);
        t.setEndDailySalesId((Integer)o[1]);
        t.setCost((Double)o[2]);
        t.setSales((Double) o[3]);
        t.setDate((Date)o[4]);
        result.add(t);
    }
    return result;
}
 
Example 8
Project: bluegreen-manager   File: JobHistoryDAO.java   Source Code and License Vote up 6 votes
/**
 * Finds the most recently started job history record matching the given jobName/env1/env2 which is no older
 * than maxAge.  Null if none found.
 */
public JobHistory findLastRelevantJobHistory(String jobName, String env1, String env2, long maxAge)
{
  String queryString = "SELECT jh FROM " + JobHistory.class.getSimpleName() + " jh WHERE "
      + "jh.jobName = '" + jobName + "' "
      + "AND jh.env1 = '" + env1 + "' "
      + "AND " + makeNullableCondition("jh.env2", env2) + " "
      + "AND jh.startTime > :oldestAllowedStartTime "
      + "ORDER BY jh.startTime DESC ";
  Query query = entityManager.createQuery(queryString);
  query.setParameter("oldestAllowedStartTime", makeTimestampBeforeNow(maxAge));
  query.setMaxResults(1);
  List<JobHistory> results = query.getResultList();
  if (results != null && results.size() > 0)
  {
    return results.get(0);
  }
  else
  {
    return null;
  }
}
 
Example 9
Project: marathonv5   File: LiveSalesListFacadeREST.java   Source Code and License Vote up 6 votes
@GET
@Produces({"application/xml", "application/json"})
@Path("/recent/producttype/{id}/{orderLineId}")
public List<LiveSalesList> findRecentProductTypeFrom(@PathParam("id") Integer productTypeId, @PathParam("orderLineId") Integer orderLineId) {
    CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
    javax.persistence.criteria.CriteriaQuery cq = cb.createQuery();
    Root<LiveSalesList> liveSalesList = cq.from(LiveSalesList.class);
    cq.select(liveSalesList);
    cq.where(cb.and(
        cb.equal(liveSalesList.get(LiveSalesList_.productTypeId), productTypeId),
        cb.gt(liveSalesList.get(LiveSalesList_.orderLineId), orderLineId)
    ));
    Query q = getEntityManager().createQuery(cq);
    q.setMaxResults(500);
    return q.getResultList();
}
 
Example 10
Project: tianti   File: CustomBaseSqlDaoImpl.java   Source Code and License Vote up 6 votes
@SuppressWarnings("rawtypes")
public List queryByMapParams(String hql, Map<String, Object> params, Integer currentPage,Integer pageSize){
	//EntityManager em = this.emf.createEntityManager();
	Query query = em.createQuery(hql);
	List list = null;
	try {
		if(params != null && !params.isEmpty()){
			for(Map.Entry<String,Object> entry: params.entrySet()){
				query.setParameter(entry.getKey(), entry.getValue());
			}
		}
		
		if(currentPage != null && pageSize != null){
			query.setFirstResult((currentPage-1)*pageSize);
			query.setMaxResults(pageSize);
		}
		list = query.getResultList();
	} catch (Exception e) {
		e.printStackTrace();
	}finally{
		em.close();
	}
	
	return list;
}
 
Example 11
Project: testing_security_development_enterprise_systems   File: MenuEJB.java   Source Code and License Vote up 5 votes
public Menu getPrevious(@NotNull LocalDate current) {
    Query query = em.createQuery("select m from Menu m where (m.date < :current) order by m.date DESC ");
    query.setParameter("current", current);
    query.setMaxResults(1);

    List list = query.getResultList();
    if (list.isEmpty()) {
        return null;
    } else {
        return (Menu) list.get(0);
    }
}
 
Example 12
Project: testing_security_development_enterprise_systems   File: DishEJB.java   Source Code and License Vote up 5 votes
public boolean canBeDeleted(long id){

        Dish dish = getDish(id);
        if(dish == null){
            return false;
        }

        Query query = em.createQuery("select m from Menu m where :dish member of m.dishes");
        query.setParameter("dish", dish);
        query.setMaxResults(1);
        List results = query.getResultList();

        return results==null || results.isEmpty();
    }
 
Example 13
Project: marathonv5   File: LiveSalesListFacadeREST.java   Source Code and License Vote up 5 votes
@GET
@Produces({"application/xml", "application/json"})
@Path("/recent/")
public List<LiveSalesList> findRecent() {
    javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
    cq.select(cq.from(LiveSalesList.class));
    Query q = getEntityManager().createQuery(cq);
    q.setMaxResults(500);
    return q.getResultList();
}
 
Example 14
Project: testing_security_development_enterprise_systems   File: MenuEJB.java   Source Code and License Vote up 5 votes
public Menu getNext(@NotNull LocalDate current) {
    Query query = em.createQuery("select m from Menu m where (m.date > :current) order by m.date ASC ");
    query.setParameter("current", current);
    query.setMaxResults(1);

    List list = query.getResultList();
    if (list.isEmpty()) {
        return null;
    } else {
        return (Menu) list.get(0);
    }
}
 
Example 15
Project: oscm   File: UserSubscriptionDao.java   Source Code and License Vote up 5 votes
private void setPaginationParameters(PaginationInt pagination,
        Query query) {
    setSortingParameter(query, pagination);
    setFilterParameters(query, pagination);

    query.setFirstResult(pagination.getOffset());
    query.setMaxResults(pagination.getLimit());
}
 
Example 16
Project: oscm   File: SharesDataRetrievalServiceBean.java   Source Code and License Vote up 5 votes
private OrganizationHistory loadVendorHistoryOfProduct(long serviceKey) {
    Query query = dm
            .createNamedQuery("OrganizationHistory.findVendorOfProduct");
    query.setParameter("productKey", Long.valueOf(serviceKey));
    query.setMaxResults(1);
    try {
        return (OrganizationHistory) query.getSingleResult();
    } catch (NoResultException e) {
        return null;
    }
}
 
Example 17
Project: tianti   File: CustomBaseSqlDaoImpl.java   Source Code and License Vote up 5 votes
/**
 * 根据SQL语句查询分页
 * @param sql
 * @param currentPage
 * @param pageSize
 * @return
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public PageModel queryForPageBySql(String sql,Integer currentPage,Integer pageSize){
	PageModel page = new PageModel();
	Integer totalCount = 0;
	Integer totalPage = 0;
	
	//EntityManager em = this.emf.createEntityManager();
	Query qry = em.createNativeQuery(sql);
	Query qry2 = em.createNativeQuery(sql);
	SQLQuery s = qry.unwrap(SQLQuery.class);
	if (currentPage != null && pageSize != null) {//判断是否有分页
		// 起始对象位置
		qry.setFirstResult(pageSize * (currentPage - 1));
		// 查询对象个数
		qry.setMaxResults(pageSize);
	}
	s.setResultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP);
	List<Map> resultList=new ArrayList<Map>();
	List list = qry2.getResultList();
	totalCount = (list == null ? 0 : list.size());
	if(totalCount % pageSize == 0){
		totalPage = totalCount/pageSize;
	}else{
		totalPage = totalCount/pageSize + 1;
	}
	try {
		resultList=s.list();
		page.setCurrentPage(currentPage);
		page.setPageSize(pageSize);
		page.setList(resultList);
		page.setTotalCount(totalCount);
		page.setTotalPage(totalPage);
	} catch (Exception e) {
		e.printStackTrace();
	}finally{
		em.close();
	}		
	return page;
}
 
Example 18
Project: oscm   File: UserGroupDao.java   Source Code and License Vote up 5 votes
public List<Product> getVisibleServices(String unitId,
        Pagination pagination, String marketplaceId) {
    Query query = dm.createNamedQuery("UserGroup.findVisibleServices");
    query.setParameter("userGroupKey", Long.valueOf(unitId));
    query.setParameter("marketplaceKey", Long.valueOf(marketplaceId));
    query.setFirstResult(pagination.getOffset());
    query.setMaxResults(pagination.getLimit());
    List<Product> visibleProducts = ParameterizedTypes.list(
            query.getResultList(), Product.class);
    return visibleProducts;
}
 
Example 19
Project: oscm   File: UserGroupDao.java   Source Code and License Vote up 5 votes
public List<Product> getAccessibleServices(String unitId,
        Pagination pagination, String marketplaceId) {
    Query query = dm.createNamedQuery("UserGroup.findAccessibleServices");
    query.setParameter("userGroupKey", Long.valueOf(unitId));
    query.setParameter("marketplaceKey", Long.valueOf(marketplaceId));
    query.setFirstResult(pagination.getOffset());
    query.setMaxResults(pagination.getLimit());
    List<Product> accessibleProducts = ParameterizedTypes.list(
            query.getResultList(), Product.class);
    return accessibleProducts;
}
 
Example 20
Project: testing_security_development_enterprise_systems   File: CommentService.java   Source Code and License Vote up 3 votes
public List<Comment> getMostRecentComments(int max){

        Query query = em.createQuery("select c from Comment c order by c.date DESC ");
        query.setMaxResults(max);

        return query.getResultList();
    }