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

The following examples show how to use javax.persistence.Query#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: LocalDatabaseIdBuilder.java    From mPaaS with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Transactional(rollbackFor = {})
@Override
public String getDatabaseId() {
	Query query = entityManager
			.createQuery("select fdId from SysEmpty order by fdId");
	query.setFirstResult(0);
	query.setMaxResults(1);
	List<String> list = query.getResultList();
	if (!list.isEmpty()) {
		return list.get(0);
	}
	SysEmpty entity = new SysEmpty();
	entityManager.persist(entity);
	return entity.getFdId();
}
 
Example 2
Source File: CommentServiceBean.java    From bbs with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 查询用户是否评论话题
 * @param topicId 话题Id
 * @param userName 用户名称
 * @return
 */
@Transactional(readOnly=true,propagation=Propagation.NOT_SUPPORTED)
public Boolean findWhetherCommentTopic(Long topicId,String userName){
	
	String sql = "select o.id from Comment o where o.topicId=?1 and o.userName=?2 and o.isStaff=?3";
	Query query = em.createQuery(sql);	
	query.setParameter(1, topicId);
	query.setParameter(2, userName);
	query.setParameter(3, false);
	//索引开始,即从哪条记录开始
	query.setFirstResult(0);
	//获取多少条数据
	query.setMaxResults(1);
	
	List<Object> objectList = query.getResultList();
	if(objectList != null && objectList.size() >0){
		return true;
	}
	
	return false;
}
 
Example 3
Source File: ProcessRemarkDAOImpl.java    From Asqatasun with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public Collection<ProcessRemark> retrieveProcessRemarksFromProcessResultAndTestSolution(
        ProcessResult processResult, 
        TestSolution testSolution, 
        int limit) {
    Query query = entityManager.createQuery("SELECT r FROM "
            + getEntityClass().getName() + " r"
            + " left join fetch r.elementSet e"
            + " WHERE r.processResult = :processResult "
            + " AND r.issue=:testSolution"
            + " ORDER BY r.id ASC");
    query.setParameter("processResult", processResult);
    query.setParameter("testSolution", testSolution);
    /* limit = 0 or -1 means all */
    if (limit > 0) {
        query.setMaxResults(limit);
    }
    Set setItems = new LinkedHashSet(query.getResultList());
    return setItems;
}
 
Example 4
Source File: DefaultJpaRepository.java    From ueboot with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public Page findObjectBySql(StringQuery stringQuery, Pageable pageable) {
    String sql = stringQuery.getQuery();
    Assert.hasText(sql, "Sql must has text!");
    Query query = em.createNativeQuery(sql);
    NamedParams params = stringQuery.getParams();
    setQueryParams(query, params);
    query.setMaxResults(pageable.getPageSize());
    query.setFirstResult((int) pageable.getOffset());

    List resultList = query.getResultList();
    String countSql = QueryUtils.genCountQueryString(sql);

    Query countQuery = em.createNativeQuery(countSql);
    setQueryParams(countQuery, params);
    Long total = Long.valueOf(countQuery.getSingleResult().toString());

    Page page = new PageImpl(resultList, pageable, total);
    return page;
}
 
Example 5
Source File: CustomBaseSqlDaoImpl.java    From tianti with Apache License 2.0 6 votes vote down vote up
@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 6
Source File: UserServiceBean.java    From bbs with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 根据条件分页查询用户名称
 * @param jpql SQL
 * @param params 参数值
 * @param firstIndex 开始索引
 * @param maxResult 需要获取的记录数
 */
@Transactional(readOnly=true,propagation=Propagation.NOT_SUPPORTED)
public List<String> findUserNameByConditionPage(String jpql,List<Object> params,int firstIndex, int maxResult){
	
	
	
	int placeholder = 1;//占位符参数
	Query query =  em.createQuery("select o.userName from User o"+(jpql == null || "".equals(jpql.trim())? "" : " where "+jpql));
	if(params != null && params.size() >0){
		for(Object obj : params){
			query.setParameter(placeholder,obj);
			placeholder++;
		}
	}
	//索引开始,即从哪条记录开始
	query.setFirstResult(firstIndex);
	//获取多少条数据
	query.setMaxResults(maxResult);
	
	return query.getResultList();
}
 
Example 7
Source File: LiveSalesListFacadeREST.java    From marathonv5 with Apache License 2.0 6 votes vote down vote up
@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 8
Source File: LiveSalesListFacadeREST.java    From marathonv5 with Apache License 2.0 6 votes vote down vote up
@GET
@Produces({"application/xml", "application/json"})
@Path("/recent/region/{regionName}/{orderLineId}")
public List<LiveSalesList> findRecentRegionFrom(@PathParam("regionName") String regionName, @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_.region), regionName),
        cb.gt(liveSalesList.get(LiveSalesList_.orderLineId), orderLineId)
    ));
    Query q = getEntityManager().createQuery(cq);
    q.setMaxResults(500);
    return q.getResultList();
}
 
Example 9
Source File: DefaultJpaRepository.java    From ueboot with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public <S> Page<S> find(String queryString, String queryCount, NamedParams params, Pageable pageable, ResultTransformer transformer) {
    Assert.hasText(queryString, "Query must has text!");
    Assert.hasText(queryCount, "Query count must has text!");
    Assert.notNull(params, "QueryParams must not be null!");
    Assert.notNull(pageable, "PageRequest must not be null!");
    Assert.notNull(transformer, "Transformer must not be null!");

    Query query = em.createQuery(queryString);

    setQueryParams(query, params);
    query.setMaxResults(pageable.getPageSize());
    query.setFirstResult((int) pageable.getOffset());

    List<S> resultList = query.unwrap(QueryImpl.class).setResultTransformer(transformer).list();

    Query countQuery = em.createQuery(queryCount);
    setQueryParams(countQuery, params);
    Long total = (Long) countQuery.getSingleResult();

    Page<S> page = new PageImpl(resultList, pageable, total);

    return page;
}
 
Example 10
Source File: JPAMessageMapper.java    From james-project with Apache License 2.0 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public MessageUid findFirstUnseenMessageUid(Mailbox mailbox) throws MailboxException {
    try {
        JPAId mailboxId = (JPAId) mailbox.getMailboxId();
        Query query = getEntityManager().createNamedQuery("findUnseenMessagesInMailboxOrderByUid").setParameter(
                "idParam", mailboxId.getRawId());
        query.setMaxResults(1);
        List<MailboxMessage> result = query.getResultList();
        if (result.isEmpty()) {
            return null;
        } else {
            return result.get(0).getUid();
        }
    } catch (PersistenceException e) {
        throw new MailboxException("Search of first unseen message failed in mailbox " + mailbox, e);
    }
}
 
Example 11
Source File: JpaUtil.java    From javaee-lab with Apache License 2.0 5 votes vote down vote up
public void applyPagination(Query query, SearchParameters sp) {
    if (sp.getFirst() > 0) {
        query.setFirstResult(sp.getFirst());
    }
    if (sp.getPageSize() > 0) {
        query.setMaxResults(sp.getPageSize());
    } else if (sp.getMaxResults() > 0) {
        query.setMaxResults(sp.getMaxResults());
    }
}
 
Example 12
Source File: UDDIReplicationImpl.java    From juddi with Apache License 2.0 5 votes vote down vote up
private synchronized UDDIReplicationPortType getReplicationClient(String node) {
        if (cache.containsKey(node)) {
                return cache.get(node);
        }
        UDDIService svc = new UDDIService();
        UDDIReplicationPortType replicationClient = svc.getUDDIReplicationPort();
        TransportSecurityHelper.applyTransportSecurity((BindingProvider) replicationClient);

        EntityManager em = PersistenceManager.getEntityManager();
        EntityTransaction tx = em.getTransaction();
        try {
                tx.begin();
                StringBuilder sql = new StringBuilder();
                sql.append("select c from ReplicationConfiguration c order by c.serialNumber desc");
                //sql.toString();
                Query qry = em.createQuery(sql.toString());
                qry.setMaxResults(1);

                org.apache.juddi.model.ReplicationConfiguration resultList = (org.apache.juddi.model.ReplicationConfiguration) qry.getSingleResult();
                for (Operator o : resultList.getOperator()) {
                        if (o.getOperatorNodeID().equalsIgnoreCase(node)) {
                                ((BindingProvider) replicationClient).getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, o.getSoapReplicationURL());
                                cache.put(node, replicationClient);
                                return replicationClient;
                        }
                }
                tx.rollback();

        } catch (Exception ex) {
                logger.fatal("Node not found!" + node, ex);
        } finally {
                if (tx.isActive()) {
                        tx.rollback();
                }
                em.close();
        }
        //em.close();
        return null;

}
 
Example 13
Source File: DatabaseNetwork.java    From BotLibre with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Return all vertices.
 */
@SuppressWarnings("unchecked")
public synchronized List<Vertex> findAll(int pageSize, int page) {
	if (isShortTerm()) {
		return allActive();
	}
	Query query = this.entityManager.createQuery("Select v from Vertex v");
	setHints(query);
	query.setFirstResult(page * pageSize);
	query.setMaxResults(pageSize);
	return query.getResultList();
}
 
Example 14
Source File: JPAScopeStore.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public List<Scope> findByResourceServer(Map<String, String[]> attributes, String resourceServerId, int firstResult, int maxResult) {
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<ScopeEntity> querybuilder = builder.createQuery(ScopeEntity.class);
    Root<ScopeEntity> root = querybuilder.from(ScopeEntity.class);
    querybuilder.select(root.get("id"));
    List<Predicate> predicates = new ArrayList();

    predicates.add(builder.equal(root.get("resourceServer").get("id"), resourceServerId));

    attributes.forEach((name, value) -> {
        if ("id".equals(name)) {
            predicates.add(root.get(name).in(value));
        } else {
            predicates.add(builder.like(builder.lower(root.get(name)), "%" + value[0].toLowerCase() + "%"));
        }
    });

    querybuilder.where(predicates.toArray(new Predicate[predicates.size()])).orderBy(builder.asc(root.get("name")));

    Query query = entityManager.createQuery(querybuilder);

    if (firstResult != -1) {
        query.setFirstResult(firstResult);
    }
    if (maxResult != -1) {
        query.setMaxResults(maxResult);
    }

    List result = query.getResultList();
    List<Scope> list = new LinkedList<>();
    for (Object id : result) {
        list.add(provider.getStoreFactory().getScopeStore().findById((String)id, resourceServerId));
    }
    return list;

}
 
Example 15
Source File: SubscriptionDao.java    From development with Apache License 2.0 5 votes vote down vote up
private void setPaginationParameters(Pagination pagination, Query query) {
    setSortingParameter(query, pagination);
    setFilterParameters(query, pagination);

    query.setFirstResult(pagination.getOffset());
    query.setMaxResults(pagination.getLimit());
}
 
Example 16
Source File: LiveSalesListFacadeREST.java    From marathonv5 with Apache License 2.0 5 votes vote down vote up
@GET
@Produces({"application/xml", "application/json"})
@Path("/recent/producttype/{id}")
public List<LiveSalesList> findRecentProductType(@PathParam("id") Integer productTypeId) {
    CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
    javax.persistence.criteria.CriteriaQuery cq = cb.createQuery();
    Root<LiveSalesList> liveSalesList = cq.from(LiveSalesList.class);
    cq.select(liveSalesList);
    cq.where(cb.equal(liveSalesList.get(LiveSalesList_.productTypeId), productTypeId));
    Query q = getEntityManager().createQuery(cq);
    q.setMaxResults(500);
    return q.getResultList();
}
 
Example 17
Source File: LiveSalesListFacadeREST.java    From marathonv5 with Apache License 2.0 5 votes vote down vote up
@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 18
Source File: PushPreProcessingServlet.java    From solutions-ios-push-notification-sample-backend-java with Apache License 2.0 4 votes vote down vote up
private void preprocessBatchOfDevices(String alertMessage, String cursorString) {
  EntityManager mgr = null;
  Cursor cursor = null;

  try {
    mgr = getEntityManager();

    // Retrieve entities (and not just deviceToken property) in order to paginate using cursor
    Query query = mgr.createQuery("select from DeviceRegistration as DeviceRegistration");
    if (cursorString != null && cursorString != "") {
      cursor = Cursor.fromWebSafeString(cursorString);
      query.setHint(JPACursorHelper.CURSOR_HINT, cursor);
    }

    query.setMaxResults(BATCH_SIZE);

    @SuppressWarnings("unchecked")
    List<DeviceRegistration> deviceRegistrations = query.getResultList();
    cursor = JPACursorHelper.getCursor(deviceRegistrations);
    if (cursor != null) {
      cursorString = cursor.toWebSafeString();
    }

    List<String> deviceTokens = new ArrayList<String>();
    for (DeviceRegistration deviceRegistartion : deviceRegistrations) {
      deviceTokens.add(deviceRegistartion.getDeviceToken());
    }

    if (deviceTokens.isEmpty()) {
      // no more matching device tokens matching this query.
      return;
    }

    mgr.getTransaction().begin();

    try {
      PushNotificationUtility.enqueuePushAlert(alertMessage, deviceTokens);

      if (deviceRegistrations.size() == BATCH_SIZE) {
        PushNotificationUtility.continueEnqueueingPushAlertToAllDevices(
            alertMessage, cursorString);
      }

      mgr.getTransaction().commit();
    } catch (RuntimeException e) {
      if (mgr.getTransaction().isActive()) {
        mgr.getTransaction().rollback();
      }
      throw e;
    }

  } finally {
    mgr.close();
  }
}
 
Example 19
Source File: ActDAOImpl.java    From Asqatasun with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public Collection<Act> findActsByContract(
        Contract contract,
        int nbOfActs,
        int sortDirection,
        ScopeEnum scopeEnum,
        boolean onlyCompleted) {
    StringBuilder queryString = new StringBuilder();
    queryString.append("SELECT a FROM ");
    queryString.append(getEntityClass().getName());
    queryString.append(" a");
    queryString.append(" WHERE a.contract = :contract");
    queryString.append(" AND ");
    if (!onlyCompleted) {
        queryString.append("(");
    }
    queryString.append("a.status = :completedStatus");
    if (!onlyCompleted) {
        queryString.append(" OR a.status = :errorStatus)");
    }
    if (scopeEnum != null) {
        queryString.append(" AND a.scope.code = :scopeCode");
    }
    queryString.append(" ORDER BY a.endDate");
    if (sortDirection == 2) {
        queryString.append(DESC_STR);
    } else {
        queryString.append(ASC_STR);
    }
    Query query = entityManager.createQuery(queryString.toString());
    query.setParameter("contract", contract);
    query.setParameter("completedStatus", ActStatus.COMPLETED);
    if (!onlyCompleted) {
        query.setParameter("errorStatus", ActStatus.ERROR);
    }
    if (scopeEnum != null) {
        query.setParameter("scopeCode", scopeEnum);
    }
    if (nbOfActs != -1) {
        query.setMaxResults(nbOfActs);
    }
    query.setHint(CACHEABLE_OPTION, "true");
    return new LinkedHashSet<Act>(query.getResultList());
}
 
Example 20
Source File: CommentService.java    From testing_security_development_enterprise_systems with GNU Lesser General Public License v3.0 3 votes vote down vote up
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();
    }