Java Code Examples for org.hibernate.Criteria#setMaxResults()

The following examples show how to use org.hibernate.Criteria#setMaxResults() . These examples are extracted from open source projects. 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
@SuppressWarnings("unchecked")

public List<E> findByCriteriaWithAliasByOrder(Criterion criterion, String[] orderBy, Integer count, String aliasTable, Criterion aliasCriterion) {
	Criteria criteria = getCurrentSession().createCriteria(entityClass);
	criteria.add(criterion);
	criteria.createAlias(aliasTable, aliasTable, CriteriaSpecification.LEFT_JOIN).add(aliasCriterion);

	for(int i = 0; i< orderBy.length; i++){
		criteria.addOrder(Order.desc(orderBy[i]));
	}
	if(count != null){
		criteria.setMaxResults(count);
	}
	try {
		return criteria.list();
	} catch (HibernateException e) {
		logger.error("Error in findByCriteriaWithAliasByOrder for criteria : " + criteria.toString(),e);
		return null;
	}
}
 
Example 2
@SuppressWarnings("unchecked")
public List<Mpp> getMedecinePackagesFromIngredients(String searchString, String lang, List<String> types, int first, int count) {
    log.debug("Getting medecine packages from ingredients for " + searchString + " from " + first + ", count=" + count);
    Session sess = this.getSessionFactory().getCurrentSession();
    Criteria c = sess.createCriteria(Mpp.class);
    addLangRestriction(c, lang);
    addTypesRestriction(c, types);

    c.createAlias("compositions", "comp").createAlias("comp.ingredient", "ingrd");
    c.add(Restrictions.or(Restrictions.ilike("name", searchString, MatchMode.START),
            Restrictions.ilike("ingrd.name", searchString, MatchMode.START)));

    c.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
    c.setFirstResult(first);
    c.setMaxResults(count);
    c.addOrder(Order.asc("name"));
    List<Mpp> result = c.list();
    return result;
}
 
Example 3
@SuppressWarnings("unchecked")

public List<E> findByCriteriaByOrder(Criterion criterion, String[] orderBy, Integer count) {
	Criteria criteria = getCurrentSession().createCriteria(entityClass);
	criteria.add(criterion);
	for(int i = 0; i< orderBy.length; i++){
		criteria.addOrder(Order.desc(orderBy[i]));
	}
	if(count != null){
		criteria.setMaxResults(count);
	}
	try {
		return criteria.list();
	} catch (HibernateException e) {
		logger.error("Error in findbyCriteriaByOrder for criteria : " + criteria.toString(),e);
		return null;
	}
}
 
Example 4
@SuppressWarnings("unchecked")
public List<Mpp> getMedecinePackagesFromIngredients(String searchString, String lang, List<String> types, int first, int count) {
	log.debug("Getting medecine packages from ingredients for " + searchString + " from " + first + ", count=" + count);
	Session sess = getSessionFactory().getCurrentSession();
	Criteria c = sess.createCriteria(Mpp.class);
	addLangRestriction(c, lang);
	addTypesRestriction(c, types);

	c.createAlias("compositions", "comp").createAlias("comp.ingredient", "ingrd");
	c.add(Restrictions.or(Restrictions.ilike("name", searchString, MatchMode.START),
			Restrictions.ilike("ingrd.name", searchString, MatchMode.START)));

	c.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
	c.setFirstResult(first);
	c.setMaxResults(count);
	c.addOrder(Order.asc("name"));
	List<Mpp> result = c.list();
	return result;
}
 
Example 5
/**
 * Prepare the given Criteria object, applying cache settings and/or
 * a transaction timeout.
 * @param criteria the Criteria object to prepare
 * @see #setCacheQueries
 * @see #setQueryCacheRegion
 */
protected void prepareCriteria(Criteria criteria) {
	if (isCacheQueries()) {
		criteria.setCacheable(true);
		if (getQueryCacheRegion() != null) {
			criteria.setCacheRegion(getQueryCacheRegion());
		}
	}
	if (getFetchSize() > 0) {
		criteria.setFetchSize(getFetchSize());
	}
	if (getMaxResults() > 0) {
		criteria.setMaxResults(getMaxResults());
	}

	SessionHolder sessionHolder =
			(SessionHolder) TransactionSynchronizationManager.getResource(getSessionFactory());
	if (sessionHolder != null && sessionHolder.hasTimeout()) {
		criteria.setTimeout(sessionHolder.getTimeToLiveInSeconds());
	}
}
 
Example 6
@SuppressWarnings("unchecked")
@Override
public List<E> getByCriteriaByOrder(Criterion criterion, String order, String[] orderBy, Integer count) {
	List<E> fetchedList = new ArrayList<E>();
	Session session = getCurrentSession();
	Criteria criteria = session.createCriteria(entityClass);
	criteria.add(criterion);
	for(int i = 0; i< orderBy.length; i++){
		if (order != null && order.equalsIgnoreCase("desc")) {
			criteria.addOrder(Order.desc(orderBy[i]));
		} else {
			criteria.addOrder(Order.asc(orderBy[i]));
		}
	}
	if(count != null && count > 0){
		criteria.setMaxResults(count);
	}
	try {	
		fetchedList = criteria.list();
		return fetchedList;
	} catch (Exception e) {
		logger.error("getByCriteriaWithLimit failed, criteria = " + criterion.toString(), e);
		throw new HibernateException("getByCriteriaByOrder failed, criteria = " + criterion.toString());
	}
}
 
Example 7
@Override
public UserConnection getByUserIdAndProviderId(String userId,
		String providerId) {
	Criteria criteria = getHibernateTemplate().getSessionFactory().getCurrentSession().createCriteria(UserConnection.class);
       criteria.add(Restrictions.eq("userId", userId));
       criteria.add(Restrictions.eq("providerId", providerId));
       criteria.setMaxResults(1);
       return (UserConnection) criteria.uniqueResult();
}
 
Example 8
@Override
public List<Job> fetchNewJobsToBeScheduledForExecutionPerSubmissionTimePriority(int count) {
    Criteria c = sessionFactory.getCurrentSession().createCriteria(clazz);
    c.setMaxResults(count);
    c.add(Restrictions.eq("status", Job.Status.NEW));
    c.addOrder(Order.asc("submitTime"));
    return c.list();
}
 
Example 9
@Override
public List<Job> fetchNewJobsToBeScheduledForExecutionPerPriority(int count) {
    Criteria c = sessionFactory.getCurrentSession().createCriteria(clazz);
    c.setMaxResults(count);
    c.add(Restrictions.eq("status", Job.Status.NEW));
    c.addOrder(Order.asc("categoryPriority"));
    c.addOrder(Order.asc("submitTime"));
    return c.list();
}
 
Example 10
Source Project: sdudoc   File: LogDaoImpl.java    License: MIT License 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public Pager<SysLog> listLogAllByPage(int pageNo, int pageSize) {
	Session session = sessionFactory.getCurrentSession();
	Criteria criteria = session.createCriteria(SysLog.class);
	long recordTotal = ((Long) criteria.setProjection(Projections.rowCount()).uniqueResult()).longValue();
	criteria.setProjection(null);
	criteria.addOrder(Order.desc("time"));
	criteria.setFirstResult((pageNo - 1) * pageSize);
	criteria.setMaxResults(pageSize);
	List<SysLog> results = criteria.list();
	return new Pager<SysLog>(pageSize, pageNo, recordTotal, results);
}
 
Example 11
@Override
public Criteria evaluate(Session session) {
	Criteria c;
	
	if(glossary_id==null){
		c = session.createCriteria(SbiGlWord.class,"gl_word");
	}else{
		//filter by glossary
		c = session.createCriteria(SbiGlWlist.class,"wlist");
		c.createAlias("wlist.word", "gl_word");
		c.createAlias("wlist.content", "gl_cont");
		c.add(Restrictions.eq("gl_cont.glossaryId", glossary_id));
	}
	
	
	c.setProjection(Projections.projectionList().add(Projections.property("gl_word.wordId"), "wordId").add(Projections.property("gl_word.word"), "word"))
			.setResultTransformer(Transformers.aliasToBean(SbiGlWord.class));
	if (word != null && !word.isEmpty()) {
		c.add(Restrictions.like("gl_word.word", word, MatchMode.ANYWHERE).ignoreCase());
	}
	if(page!=null && item_per_page!=null ){
		c.setFirstResult((page - 1) * item_per_page);
	     c.setMaxResults(item_per_page);
		}
	c.addOrder(Order.asc("gl_word.word"));
	return c;
}
 
Example 12
@SuppressWarnings("unchecked")

public List<E> getMaxOrderByCriteria(Criterion criterion, String orderBy) {
	Criteria criteria = getCurrentSession().createCriteria(entityClass);
	criteria.add(criterion);
	criteria.addOrder(Order.desc(orderBy));
	criteria.setMaxResults(1);
	try {
		return criteria.list();
	} catch (HibernateException e) {
		logger.error("Error in getMaxOrderByCriteria for criteria : " + criteria.toString(),e);
		return null;
	}
}
 
Example 13
Source Project: framework   File: BaseHibernateDao.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Description: <br>
 * 
 * @author 王伟<br>
 * @taskId <br>
 * @param detachedCriteria
 * @param pi
 * @param pageSize
 * @param <T> T
 * @return T
 * @throws DaoException <br>
 */
@Override
public <T> PagerList<T> getPageList(final DetachedCriteria detachedCriteria, final int pi, final int pageSize)
    throws DaoException {
    int pageIndex = pi;
    if (pi == 0) {
        pageIndex = 1;
    }

    Criteria criteria = detachedCriteria.getExecutableCriteria(getSession());

    // 查询分页总数
    CriteriaImpl impl = (CriteriaImpl) criteria;
    Projection projection = impl.getProjection();
    Long allCounts = (Long) criteria.setProjection(Projections.rowCount()).uniqueResult();

    criteria.setProjection(projection);
    criteria.setFirstResult((pageIndex - 1) * pageSize);
    criteria.setMaxResults(pageSize);

    PagerList<T> resultList = new PagerList<T>();
    resultList.setPageIndex(pageIndex);
    resultList.setPageSize(pageSize);
    if (allCounts == null) {
        allCounts = 0L;
    }
    resultList.setTotalCount(allCounts);

    if (allCounts > 0) {
        resultList.addAll(criteria.list());
    }
    return resultList;
}
 
Example 14
Source Project: jeewx   File: GenericBaseCommonDao.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 根据CriteriaQuery获取List
 * 
 * @param cq
 * @param isOffset
 * @return
 */
@SuppressWarnings("unchecked")
public List<T> getListByCriteriaQuery(final CriteriaQuery cq, Boolean ispage) {
	Criteria criteria = cq.getDetachedCriteria().getExecutableCriteria(
			getSession());
	// 判断是否有排序字段
	if (cq.getOrdermap() != null) {
		cq.setOrder(cq.getOrdermap());
	}
	if (ispage)
		criteria.setMaxResults(cq.getPageSize());
	return criteria.list();

}
 
Example 15
@Override
public List<Job> fetchFailedJobsToBeScheduledForExecutionPerSubmissionTimePriority(int count) {
    Criteria c = sessionFactory.getCurrentSession().createCriteria(clazz);
    c.setMaxResults(count);
    c.add(Restrictions.eq("status", Job.Status.FAILED));
    c.addOrder(Order.asc("submitTime"));
    return c.list();
}
 
Example 16
Source Project: tutorials   File: UserDao.java    License: MIT License 5 votes vote down vote up
public User findByEmail(String email) {
    Session session = sessionFactory.openSession();
    session.beginTransaction();
    Criteria criteria = session.createCriteria(User.class);
    criteria.add(Restrictions.eq("email", email));
    criteria.setMaxResults(1);
    User u = (User) criteria.uniqueResult();
    session.getTransaction().commit();
    session.close();
    return u;
}
 
Example 17
Source Project: sdudoc   File: BookDaoImpl.java    License: MIT License 5 votes vote down vote up
@Override
public Pager<Book> searchByAuthor(String author, int pageNo, int pageSize) {
	Session session = sessionFactory.getCurrentSession();
	Criteria criteria = session.createCriteria(Book.class);
	criteria.add(Restrictions.like("authors", "%"+author+"%"));
	long recordTotal = ((Long) criteria.setProjection(Projections.rowCount()).uniqueResult()).longValue();
	criteria.setProjection(null);
//	criteria.addOrder(Order.desc("clickTimes"));
	criteria.setFirstResult((pageNo - 1) * pageSize);
	criteria.setMaxResults(pageSize);
	List<Book> results = criteria.list();
	Pager<Book> page=new Pager<Book>(pageSize, pageNo, recordTotal, results);
	return page;
}
 
Example 18
/**
 * 
 * @see getChannelMessages
 */
@SuppressWarnings("unchecked")
protected List<ChatMessage> getChannelMessages(ChatChannel channel, Date date, int start, int max, boolean sortAsc) throws PermissionException {

    List<ChatMessage> messages = new ArrayList<>();
    if (channel == null || max == 0) {
        // no channel or no items causes nothing to be returned
        return messages;
    }

    checkPermission(ChatFunctions.CHAT_FUNCTION_READ, channel.getContext());
    int localMax = max;
    int localStart = start;
    Date localDate = date;

    // Find out which values to use.
    // If the settings of the channel have more strict values then the passed info, use them instead.
    if (channel.getFilterType().equals(ChatChannel.FILTER_BY_NUMBER) || 
            channel.getFilterType().equals(ChatChannel.FILTER_NONE)) {
        if (!channel.isEnableUserOverride()) {
            localMax = Math.min(localMax, channel.getFilterParam());
        }
    } else if (channel.getFilterType().equals(ChatChannel.FILTER_BY_TIME)) {
        int days = channel.getFilterParam();
        Date tmpDate = calculateDateByOffset(days);
        if (!channel.isEnableUserOverride()) {
            localDate = tmpDate;
        }
    }

    // enforce maximum number of messages returned
    if (localStart < 0) {
        localStart = 0;
    }
    if (localMax < 0 || localMax > messagesMax) {
        localMax = messagesMax;
    }

    Criteria c = this.getSessionFactory().getCurrentSession().createCriteria(ChatMessage.class);
    c.add(Expression.eq("chatChannel", channel));      
    if (localDate != null) {
        c.add(Expression.ge("messageDate", localDate));
    }

    // Always sort desc so we get the newest messages, reorder after we get the final list
    c.addOrder(Order.desc("messageDate"));

    if (localStart > 0) {
        c.setFirstResult(localStart);
    }

    // Date settings should always override the max message setting
    if (localMax > 0) {
        c.setMaxResults(localMax);
    }

    messages = c.list();

    //Reorder the list
    if (sortAsc) {
        Collections.sort(messages, channelComparatorAsc);
    } else {
        Collections.sort(messages, channelComparatorDesc);
    }

    return messages;
}
 
Example 19
@SuppressWarnings("unchecked")
@Override
public List<Collection> getStoppedCollections(Integer start, Integer limit, String terms, String sortColumn, String sortDirection) {
	Criteria criteriaIds = getHibernateTemplate().getSessionFactory().getCurrentSession().createCriteria(Collection.class);
	criteriaIds.setProjection(Projections.projectionList()
			.add(Projections.property("id"), "id"));

	LogicalExpression or = Restrictions.or(
			Restrictions.eq("status", CollectionStatus.STOPPED),
			Restrictions.eq("status", CollectionStatus.NOT_RUNNING)
			);
	
	LogicalExpression orAll = Restrictions.or(
			or,
			Restrictions.eq("status", CollectionStatus.FATAL_ERROR)
			);
	
	criteriaIds.add(orAll);
	addCollectionSearchCriteria(terms, criteriaIds);
	searchCollectionsAddOrder(sortColumn, sortDirection, criteriaIds);

	if (start != null) {
		criteriaIds.setFirstResult(start);
	}
	if (limit != null) {
		criteriaIds.setMaxResults(limit);
	}

	List<Integer> ids = criteriaIds.list();

	if (ids.size() == 0){
		return Collections.emptyList();
	}

	Criteria criteria = getHibernateTemplate().getSessionFactory().getCurrentSession().createCriteria(Collection.class);
	criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);

	criteria.add(Restrictions.in("id", ids));
	searchCollectionsAddOrder(sortColumn, sortDirection, criteria);

	return criteria.list();
}
 
Example 20
Source Project: uflo   File: ProcessQueryImpl.java    License: Apache License 2.0 4 votes vote down vote up
private void buildCriteria(Criteria criteria,boolean queryCount){
	if(!queryCount && firstResult>0){
		criteria.setFirstResult(firstResult);			
	}
	if(!queryCount && maxResults>0){
		criteria.setMaxResults(maxResults);			
	}
	if(id>0){
		criteria.add(Restrictions.eq("id", id));
	}
	if(StringUtils.isNotEmpty(name)){
		criteria.add(Restrictions.like("name", name));
	}
	if(StringUtils.isNotEmpty(key)){
		criteria.add(Restrictions.like("key", key));
	}
	if(StringUtils.isNotEmpty(subject)){
		criteria.add(Restrictions.like("subject", subject));
	}
	if(createDateLessThen!=null){
		criteria.add(Restrictions.lt("createDate", createDateLessThen));
	}
	if(createDateGreaterThen!=null){
		criteria.add(Restrictions.gt("createDate", createDateGreaterThen));
	}
	if(createDateLessThenOrEquals!=null){
		criteria.add(Restrictions.le("createDate", createDateLessThenOrEquals));
	}
	if(createDateGreaterThenOrEquals!=null){
		criteria.add(Restrictions.ge("createDate", createDateGreaterThenOrEquals));
	}
	if(StringUtils.isNotEmpty(categoryId)){
		criteria.add(Restrictions.eq("categoryId", categoryId));
	}else{
		categoryId=EnvironmentUtils.getEnvironment().getCategoryId();
		if(StringUtils.isNotEmpty(categoryId)){
			criteria.add(Restrictions.eq("categoryId", categoryId));
		}
	}
	if(StringUtils.isNotBlank(category)) {
		criteria.add(Restrictions.eq("category", category));
	}
	if(version>0){
		criteria.add(Restrictions.eq("version", Integer.valueOf(version)));
	}
	if(!queryCount){
		for(String ascProperty:ascOrders){
			criteria.addOrder(Order.asc(ascProperty));
		}
		for(String descProperty:descOrders){
			criteria.addOrder(Order.desc(descProperty));
		}
	}
}