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

The following examples show how to use org.hibernate.Criteria#setFirstResult() . 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<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 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 = 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
Source Project: sdudoc   File: BookDaoImpl.java    License: MIT License 6 votes vote down vote up
@Override
public Pager<Book> showBookByDynasty(String dynasty, int pageNo,int pageSize) {
	System.out.println("-----执行到BookDaoImpl");
	
	Session session = sessionFactory.getCurrentSession();
	Criteria criteria = session.createCriteria(Book.class);
	criteria.add(Restrictions.eq("dynasty", dynasty));
	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 4
Source Project: sdudoc   File: BookDaoImpl.java    License: MIT License 6 votes vote down vote up
@Override
public Pager<Book> searchByTitle(String title, int pageNo, int pageSize) {
	
	Session session = sessionFactory.getCurrentSession();
	Criteria criteria = session.createCriteria(Book.class);
	criteria.add(Restrictions.like("bookTitle", "%"+title+"%"));
	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();
	System.out.println(results.size()+"-------数据多少");
	Pager<Book> page=new Pager<Book>(pageSize, pageNo, recordTotal, results);
	return page;
}
 
Example 5
@SuppressWarnings("unchecked")
@Test
public final void givenUsingTheCriteriaApi_whenRetrievingPaginatedData_thenCorrect() {
    final Criteria criteriaCount = session.createCriteria(Foo.class);
    criteriaCount.setProjection(Projections.rowCount());
    final Long count = (Long) criteriaCount.uniqueResult();

    int pageNumber = 1;
    final int pageSize = 10;
    final List<Foo> fooList = Lists.newArrayList();

    final Criteria criteria = session.createCriteria(Foo.class);
    int totalEntities = 0;
    while (totalEntities < count.intValue()) {
        criteria.setFirstResult((pageNumber - 1) * pageSize);
        criteria.setMaxResults(pageSize);
        fooList.addAll(criteria.list());
        totalEntities = fooList.size();
        pageNumber++;
    }
}
 
Example 6
Source Project: jeecg   File: GenericBaseCommonDao.java    License: Apache License 2.0 6 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.setFirstResult((cq.getCurPage()-1)*cq.getPageSize());
		criteria.setMaxResults(cq.getPageSize());
	}
	return criteria.list();

}
 
Example 7
Source Project: jeecg   File: GenericBaseCommonDao.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 获取分页记录CriteriaQuery 老方法final int allCounts =
 * oConvertUtils.getInt(criteria
 * .setProjection(Projections.rowCount()).uniqueResult(), 0);
 *
 * @param cq
 * @param isOffset
 * @return
 */
public PageList getPageList(final CriteriaQuery cq, final boolean isOffset) {

	Criteria criteria = cq.getDetachedCriteria().getExecutableCriteria(
			getSession());
	CriteriaImpl impl = (CriteriaImpl) criteria;
	// 先把Projection和OrderBy条件取出来,清空两者来执行Count操作
	Projection projection = impl.getProjection();
	final int allCounts = ((Long) criteria.setProjection(
			Projections.rowCount()).uniqueResult()).intValue();
	criteria.setProjection(projection);
	if (projection == null) {
		criteria.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);
	}

	// 判断是否有排序字段
	if (cq.getOrdermap() != null) {
		cq.setOrder(cq.getOrdermap());
	}
	int pageSize = cq.getPageSize();// 每页显示数
	int curPageNO = PagerUtil.getcurPageNo(allCounts, cq.getCurPage(),
			pageSize);// 当前页
	int offset = PagerUtil.getOffset(allCounts, curPageNO, pageSize);
	String toolBar = "";
	if (isOffset) {// 是否分页
		criteria.setFirstResult(offset);
		criteria.setMaxResults(cq.getPageSize());
		if (cq.getIsUseimage() == 1) {
			toolBar = PagerUtil.getBar(cq.getMyAction(), cq.getMyForm(),
					allCounts, curPageNO, pageSize, cq.getMap());
		} else {
			toolBar = PagerUtil.getBar(cq.getMyAction(), allCounts,
					curPageNO, pageSize, cq.getMap());
		}
	} else {
		pageSize = allCounts;
	}
	return new PageList(criteria.list(), toolBar, offset, curPageNO,
			allCounts);
}
 
Example 8
public static void applyLimit(Integer limit, Integer defaultLimit, Criteria criteria) {
	if (criteria != null) {
		criteria.setFirstResult(0);
		if (limit != null) {
			if (limit >= 0) {
				criteria.setMaxResults(limit);
			}
		} else if (defaultLimit != null) {
			if (defaultLimit >= 0) {
				criteria.setMaxResults(defaultLimit);
			}
		}
	}
}
 
Example 9
Source Project: jeecg   File: GenericBaseCommonDao.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 返回JQUERY datatables DataTableReturn模型对象
 */
public DataTableReturn getDataTableReturn(final CriteriaQuery cq,
		final boolean isOffset) {

	Criteria criteria = cq.getDetachedCriteria().getExecutableCriteria(
			getSession());
	CriteriaImpl impl = (CriteriaImpl) criteria;
	// 先把Projection和OrderBy条件取出来,清空两者来执行Count操作
	Projection projection = impl.getProjection();
	final int allCounts = ((Long) criteria.setProjection(
			Projections.rowCount()).uniqueResult()).intValue();
	criteria.setProjection(projection);
	if (projection == null) {
		criteria.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);
	}

	// 判断是否有排序字段
	if (cq.getOrdermap() != null) {
		cq.setOrder(cq.getOrdermap());
	}
	int pageSize = cq.getPageSize();// 每页显示数
	int curPageNO = PagerUtil.getcurPageNo(allCounts, cq.getCurPage(),
			pageSize);// 当前页
	int offset = PagerUtil.getOffset(allCounts, curPageNO, pageSize);
	if (isOffset) {// 是否分页
		criteria.setFirstResult(offset);
		criteria.setMaxResults(cq.getPageSize());
	} else {
		pageSize = allCounts;
	}

	//DetachedCriteriaUtil.selectColumn(cq.getDetachedCriteria(), cq.getField().split(","), cq.getEntityClass(), false);

	
	return new DataTableReturn(allCounts, allCounts, cq.getDataTables().getEcho(), criteria.list());
}
 
Example 10
Source Project: jeecg   File: GenericBaseCommonDao.java    License: Apache License 2.0 5 votes vote down vote up
public <T> List<T> pageList(DetachedCriteria dc, int firstResult,
		int maxResult) {
	Criteria criteria = dc.getExecutableCriteria(getSession());
	criteria.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);
	criteria.setFirstResult(firstResult);
	criteria.setMaxResults(maxResult);
	return criteria.list();
}
 
Example 11
Source Project: TinyMooc   File: BaseServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 当前页数据
 *
 * @param clazz
 * @param pageSize
 * @param <T>
 * @return List<T>
 */
@SuppressWarnings("unchecked")
@Transactional(readOnly = true)
public <T> List<T> getByPage(Class<T> clazz, int pageSize) {
    int curPage = PageHelper.getCurPage();
    if (curPage < 1)
        curPage = 1;
    Criteria criteria = getCurrentSession().createCriteria(clazz);
    criteria.setFirstResult((curPage - 1) * pageSize);
    criteria.setMaxResults(pageSize);
    List<T> list = criteria.list();
    return list;
}
 
Example 12
/**
 * Load paginated tables.
 *
 * @return List of meta tables
 *
 * @throws EMFUserError
 *             the EMF user error
 *
 * @see it.eng.spagobi.metadata.dao.ISbiMetaTableDAOHibImpl#loadAllTables()
 */
@Override
public List<SbiMetaTable> loadPaginatedTables(Integer page, Integer item_per_page, String search) throws EMFUserError {
	logger.debug("IN");

	Session tmpSession = null;
	Transaction tx = null;
	List<SbiMetaTable> toReturn = new ArrayList();
	try {
		tmpSession = getSession();
		tx = tmpSession.beginTransaction();

		Criteria c = tmpSession.createCriteria(SbiMetaTable.class);
		c.addOrder(Order.asc("name"));

		c.setFirstResult((page - 1) * item_per_page);
		c.setMaxResults(item_per_page);

		c.add(Restrictions.like("name", search == null ? "" : search, MatchMode.ANYWHERE).ignoreCase());
		tx.commit();
		toReturn = c.list();
	} catch (HibernateException he) {
		logException(he);

		if (tx != null)
			tx.rollback();

		throw new EMFUserError(EMFErrorSeverity.ERROR, 100);

	} finally {

		if (tmpSession != null) {
			if (tmpSession.isOpen())
				tmpSession.close();
		}

	}
	logger.debug("OUT");
	return toReturn;
}
 
Example 13
private void buildCriteria(Criteria criteria,boolean queryCount){
	if(!queryCount && firstResult>0){
		criteria.setFirstResult(firstResult);			
	}
	if(!queryCount && maxResults>0){
		criteria.setMaxResults(maxResults);			
	}
	criteria.add(Restrictions.isNotNull("endDate"));
	if(processId>0){
		criteria.add(Restrictions.eq("processId", processId));
	}
	if(StringUtils.isNotEmpty(businessId)){
		criteria.add(Restrictions.eq("businessId", businessId));
	}
	if(StringUtils.isNotEmpty(tag)){
		criteria.add(Restrictions.eq("tag", tag));
	}
	if(StringUtils.isNotEmpty(promoter)){
		criteria.add(Restrictions.eq("promoter", promoter));
	}
	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(!queryCount){
		for(String ascProperty:ascOrders){
			criteria.addOrder(Order.asc(ascProperty));
		}
		for(String descProperty:descOrders){
			criteria.addOrder(Order.desc(descProperty));
		}
	}
}
 
Example 14
@Override
public List<SbiDataSet> loadPaginatedSearchSbiDataSet(String search, Integer page, Integer item_per_page, IEngUserProfile finalUserProfile,
		Boolean seeTechnical, Integer[] ids, boolean spatialOnly) {
	Session session = null;
	List<SbiDataSet> list = null;

	try {
		session = getSession();
		Criteria c = session.createCriteria(SbiDataSet.class);
		c.addOrder(Order.asc("label"));

		if (page != null && item_per_page != null) {
			c.setFirstResult((page - 1) * item_per_page);
			c.setMaxResults(item_per_page);
		}

		c.add(Restrictions.like("label", search == null ? "" : search, MatchMode.ANYWHERE).ignoreCase());
		c.add(Restrictions.eq("active", true));

		if (ids != null && ids.length > 0) {
			c.add(Restrictions.in("id.dsId", ids));
		}

		if (spatialOnly) {
			c.add(Restrictions.like("dsMetadata", IFieldMetaData.FieldType.SPATIAL_ATTRIBUTE.toString(), MatchMode.ANYWHERE));
		}

		if (finalUserProfile != null) {

			logger.debug("For final user take only owned, enterprise and shared");

			SbiDomains scopeUserDomain = DAOFactory.getDomainDAO().loadSbiDomainByCodeAndValue("DS_SCOPE", SpagoBIConstants.DS_SCOPE_USER);
			SbiDomains scopeEnterpriseDomain = DAOFactory.getDomainDAO().loadSbiDomainByCodeAndValue("DS_SCOPE", SpagoBIConstants.DS_SCOPE_ENTERPRISE);
			SbiDomains scopeTechnicalDomain = DAOFactory.getDomainDAO().loadSbiDomainByCodeAndValue("DS_SCOPE", SpagoBIConstants.DS_SCOPE_TECHNICAL);

			Disjunction or = Restrictions.disjunction();

			// OWNER OR

			// take owned datasets
			or.add(Restrictions.eq("owner", ((UserProfile) finalUserProfile).getUserId().toString()));

			// get categories
			Set<Domain> categoryList = UserUtilities.getDataSetCategoriesByUser(finalUserProfile);

			if (categoryList != null) {
				if (categoryList.size() > 0) {
					SbiDomains[] categoryArray = new SbiDomains[categoryList.size()];
					int i = 0;
					for (Iterator iterator = categoryList.iterator(); iterator.hasNext();) {
						Domain domain = (Domain) iterator.next();
						String domainCd = domain.getDomainCode();
						String valueCd = domain.getValueCd();
						SbiDomains sbiDomain = DAOFactory.getDomainDAO().loadSbiDomainByCodeAndValue(domainCd, valueCd);
						categoryArray[i] = sbiDomain;
						i++;
					}
					// (IN CATEGORY AND (SCOPE=USER OR SCOPE=ENTERPRISE)) OR SCOPE=TECHNICAL
					Conjunction andCategories = Restrictions.conjunction();
					andCategories.add(Restrictions.in("category", categoryArray));

					Disjunction orScope = Restrictions.disjunction();
					orScope.add(Restrictions.eq("scope", scopeUserDomain));
					orScope.add(Restrictions.eq("scope", scopeEnterpriseDomain));

					andCategories.add(orScope);

					if (seeTechnical != null && seeTechnical) {
						Disjunction orTechnical = Restrictions.disjunction();
						orTechnical.add(andCategories);
						orTechnical.add(Restrictions.eq("scope", scopeTechnicalDomain));
						or.add(orTechnical);
					} else {
						or.add(andCategories);
					}

				}
			} else {
				// if no categoryList take also all USER and ENTERPRISE dataset
				// SCOPE=USER OR SCOPE=ENTERPRISE)
				or.add(Restrictions.eq("scope", scopeUserDomain));
				or.add(Restrictions.eq("scope", scopeEnterpriseDomain));
			}

			c.add(or);
		}

		list = c.list();
		initialize(list);

	} catch (Exception e) {
		throw new SpagoBIDAOException("An unexpected error occured while loading datasets", e);
	} finally {
		if (session != null && session.isOpen()) {
			session.close();
		}
		logger.debug("OUT");
	}
	return list;
}
 
Example 15
@Override
@SuppressWarnings("unchecked")
public List<ModelHistoryWrapper> getModelByModelFamilyID(Long modelFamilyID, Integer start, Integer limit, 
		String sortColumn, String sortDirection) throws PropertyNotSetException {
	List<ModelDTO> modelDTOList = new ArrayList<ModelDTO>();
	List<ModelHistoryWrapper> wrapperList = new ArrayList<ModelHistoryWrapper>();
	
	Criteria criteria = getCurrentSession().createCriteria(Model.class);
	criteria.add(Restrictions.eq("modelFamily.modelFamilyId", modelFamilyID));

	if(sortColumn.isEmpty()){
		sortColumn = "trainingTime";
	}
	if(sortDirection.isEmpty()){
		sortDirection = "DESC";
		criteria.addOrder(Order.desc(sortColumn));
	}
	else{
		if(sortDirection.equalsIgnoreCase("ASC")){
			criteria.addOrder(Order.asc(sortColumn));
		}
		else if (sortDirection.equalsIgnoreCase("DESC")){
			criteria.addOrder(Order.desc(sortColumn));
		}
	}
	
	criteria.setFirstResult(start);
	criteria.setMaxResults(limit);
	List<Model> modelList = criteria.list();
	for (Model model : modelList) {
		modelDTOList.add(new ModelDTO(model));
		ModelHistoryWrapper w = new ModelHistoryWrapper();
		w.setModelID(model.getModelId());
		w.setAvgAuc(model.getAvgAuc());
		w.setAvgPrecision(model.getAvgPrecision());
		w.setAvgRecall(model.getAvgRecall());
		w.setTrainingCount(model.getTrainingCount());
		w.setTrainingTime(model.getTrainingTime());
		wrapperList.add(w);
	}
	return wrapperList;
}
 
Example 16
@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 17
/**
 * 
 * @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 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
public PagedList<EventLog> loadAllEventsLog(int offset, int fetchsize, Date startDate, Date endDate, String creationUser, String type, String sortingColumn,
		boolean sortingAscending) {
	logger.debug("IN");
	Session aSession = null;
	Transaction tx = null;
	PagedList<EventLog> toReturn = null;
	try {
		aSession = getSession();
		tx = aSession.beginTransaction();

		Criteria criteria = getBaseFilteringCriteria(startDate, endDate, creationUser, type, aSession);
		int total = getTotalNumber(criteria);

		addOrderingCriteria(criteria, sortingColumn, sortingAscending);

		criteria.setFirstResult(offset);
		criteria.setMaxResults(fetchsize);

		List hibList = criteria.list();

		Iterator it = hibList.iterator();
		List<EventLog> results = new ArrayList<EventLog>();
		while (it.hasNext()) {
			results.add(toEventsLog((SbiEventsLog) it.next()));
		}
		int start = offset + 1;
		toReturn = new PagedList<EventLog>(results, total, start);
	} catch (HibernateException he) {
		logException(he);
		if (tx != null)
			tx.rollback();
		throw new SpagoBIRuntimeException("Error loading events", he);
	} finally {
		if (aSession != null) {
			if (aSession.isOpen())
				aSession.close();
		}
		logger.debug("OUT");
	}
	return toReturn;
}
 
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));
		}
	}
}