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

The following examples show how to use org.hibernate.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: HibernateTemplate.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Prepare the given Query object, applying cache settings and/or
 * a transaction timeout.
 * @param queryObject the Query object to prepare
 * @see #setCacheQueries
 * @see #setQueryCacheRegion
 */
protected void prepareQuery(Query queryObject) {
	if (isCacheQueries()) {
		queryObject.setCacheable(true);
		if (getQueryCacheRegion() != null) {
			queryObject.setCacheRegion(getQueryCacheRegion());
		}
	}
	if (getFetchSize() > 0) {
		queryObject.setFetchSize(getFetchSize());
	}
	if (getMaxResults() > 0) {
		queryObject.setMaxResults(getMaxResults());
	}

	SessionHolder sessionHolder =
			(SessionHolder) TransactionSynchronizationManager.getResource(getSessionFactory());
	if (sessionHolder != null && sessionHolder.hasTimeout()) {
		queryObject.setTimeout(sessionHolder.getTimeToLiveInSeconds());
	}
}
 
Example 2
Source File: ProfileDaoImpl.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
/**
	 * {@inheritDoc}
	 */
@Override
public ProfileFriend getPendingConnection(final String userId, final String friendId) {
	
	if(userId == null || friendId == null){
  		throw new IllegalArgumentException("Null Argument in getPendingConnection"); 
  	}
	
	final HibernateCallback<ProfileFriend> hcb = session -> {
           final Query q = session.getNamedQuery(QUERY_GET_FRIEND_REQUEST);
           q.setParameter(USER_UUID, userId, StringType.INSTANCE);
           q.setParameter(FRIEND_UUID, friendId, StringType.INSTANCE);
           q.setParameter(CONFIRMED, false, BooleanType.INSTANCE);
           q.setMaxResults(1);
           return (ProfileFriend) q.uniqueResult();
     };

	return getHibernateTemplate().execute(hcb);
}
 
Example 3
Source File: DbManager.java    From megatron-java with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public List<Organization> searchOrganizations(String name, int startIndex,
        int noOfRecords) 
                throws DbException { 
    try {
        Query query = session.createQuery("from Organization where name like ?");
        query.setString(0, "%" + name +"%");

        query.setMaxResults(noOfRecords);
        query.setFirstResult(startIndex);

        return query.list();
    } 
    catch (Exception e) {
        throw handleException(e.getClass().getSimpleName() + " exception in searchOrganizations", e);
    }
}
 
Example 4
Source File: DbManager.java    From megatron-java with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public List<Job> searchLogJobs(Date startTime, Date endTime, int startIndex,
        int noOfRecords) 
                throws DbException { 

    try {

        Query query = session.createQuery("from Job where started >= ? and started <= ? order by Id asc");
        query.setLong(0, SqlUtil.convertTimestamp(startTime));
        query.setLong(1, SqlUtil.convertTimestamp(endTime));
        query.setMaxResults(noOfRecords);
        query.setFirstResult(startIndex);

        return query.list();
    } 
    catch (Exception e) {
        throw handleException(e.getClass().getSimpleName() + " exception in searchLogJobs", e);
    }

}
 
Example 5
Source File: RandomisedUrlService.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
/**
 * Checks if a given key is unique by checking for its existence
 * @param key
 * @return
 */
private boolean isKeyUnique(final String key) {
	
	RandomisedUrl randomisedUrl = null;
	
	HibernateCallback<RandomisedUrl> hcb = session -> {
           Query q = session.getNamedQuery(QUERY_GET_URL);
           q.setParameter(KEY, key, StringType.INSTANCE);
           q.setMaxResults(1);
           return (RandomisedUrl) q.uniqueResult();
     };

	//if null then it doesn't exist
	randomisedUrl = getHibernateTemplate().execute(hcb);
	if(randomisedUrl == null) {
		return true;
	}
	return false;
}
 
Example 6
Source File: DaoSupportImpl.java    From SmartEducation with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("rawtypes")
@Override
public PageBean getPageBean(int pageNum, int pageSize,QueryHelper queryHelper) {
	System.out.println("-------> DaoSupportImpl.getPageBean( int pageNum, int pageSize, QueryHelper queryHelper )");
	// 参数列表
	List<Object> parameters = queryHelper.getParameters();
	// 查询本页的数据列表
	Query listQuery = getSession().createQuery(queryHelper.getListQueryHql()); // 创建查询对象
	if (parameters != null) { // 设置参数
		for (int i = 0; i < parameters.size(); i++) {
			listQuery.setParameter(i, parameters.get(i));
		}
	}
	listQuery.setFirstResult((pageNum - 1) * pageSize);
	listQuery.setMaxResults(pageSize);
	List list = listQuery.list(); // 执行查询
	// 查询总记录数量
	Query countQuery = getSession().createQuery(queryHelper.getCountQueryHql());
	if (parameters != null) { // 设置参数
		for (int i = 0; i < parameters.size(); i++) {
			countQuery.setParameter(i, parameters.get(i));
		}
	}
	Long count = (Long) countQuery.uniqueResult(); // 执行查询
	return new PageBean(pageNum, pageSize, count.intValue(), list);
}
 
Example 7
Source File: TimeLineDAOimpl.java    From ALLGO with Apache License 2.0 6 votes vote down vote up
@Override
public List<EventVo> getFriendEvent(int uid, int page, int pagenum) {
	List<EventVo> listVo = null;
	Session session=HibernateSessionFactory.getSession();
	session.clear();
	String hql="select vo.fid from UserFriendVo vo where vo.uid=:uid";
	Query query=session.createQuery(hql);
	query.setParameter("uid",uid);
	query.setFirstResult((page-1)*pagenum);
	query.setMaxResults(pagenum);
	List<Integer> list = query.list();
	for(int i=0;i<list.size();i++){
		int fid = (int) list.get(i);
		String hql2="from EventVo vo where vo.uid=:fid";
		Query query2=session.createQuery(hql2);
		query2.setParameter("fid",fid);
		if(listVo == null){
			listVo = new ArrayList<EventVo>();
		}
		listVo.addAll(query2.list());
	}
	if(listVo ==null||listVo.size() == 0){
		list = null;
	}
	return listVo;
}
 
Example 8
Source File: ChangeLog.java    From unitime with Apache License 2.0 6 votes vote down vote up
public static List findLastNChanges(Long sessionId, Long managerId, Long subjAreaId, Long departmentId, int n) {
    try {
        org.hibernate.Session hibSession = new ChangeLogDAO().getSession(); 
        Query q = hibSession.createQuery(
                    "select ch from ChangeLog ch where " +
                    "ch.session.uniqueId=:sessionId " +
                    (managerId==null?"":"and ch.manager.uniqueId=:managerId ") +
                    (subjAreaId==null?"":"and ch.subjectArea.uniqueId=:subjAreaId ") +
                    (departmentId==null?"":"and ch.department.uniqueId=:departmentId ") + 
                    "order by ch.timeStamp desc");
        q.setLong("sessionId", sessionId.longValue());
        if (managerId!=null) q.setLong("managerId",managerId.longValue());
        if (subjAreaId!=null) q.setLong("subjAreaId",subjAreaId.longValue());
        if (departmentId!=null) q.setLong("departmentId",departmentId.longValue());
        q.setMaxResults(n);
        q.setCacheable(true);
        return q.list();
    } catch (Exception e) {
        Debug.error(e);
    }
    return null;
}
 
Example 9
Source File: RandomisedUrlService.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
/**
 * Checks if a given key is unique by checking for its existence
 * @param key
 * @return
 */
private boolean isKeyUnique(final String key) {
	
	RandomisedUrl randomisedUrl = null;
	
	HibernateCallback<RandomisedUrl> hcb = session -> {
           Query q = session.getNamedQuery(QUERY_GET_URL);
           q.setParameter(KEY, key, StringType.INSTANCE);
           q.setMaxResults(1);
           return (RandomisedUrl) q.uniqueResult();
     };

	//if null then it doesn't exist
	randomisedUrl = getHibernateTemplate().execute(hcb);
	if(randomisedUrl == null) {
		return true;
	}
	return false;
}
 
Example 10
Source File: ProfileDaoImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
	 * {@inheritDoc}
	 */
@Override
public ProfilePreferences getPreferencesRecordForUser(final String userId) {
	
	final HibernateCallback<ProfilePreferences> hcb = session -> {
           final Query q = session.getNamedQuery(QUERY_GET_PREFERENCES_RECORD);
           q.setParameter(USER_UUID, userId, StringType.INSTANCE);
           q.setMaxResults(1);
           return (ProfilePreferences) q.uniqueResult();
     };

	return getHibernateTemplate().execute(hcb);
}
 
Example 11
Source File: ProfileDaoImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
	 * {@inheritDoc}
	 */
@Override
public ProfilePrivacy getPrivacyRecord(final String userId) {
	
	final HibernateCallback<ProfilePrivacy> hcb = session -> {
           final Query q = session.getNamedQuery(QUERY_GET_PRIVACY_RECORD);
           q.setParameter(USER_UUID, userId, StringType.INSTANCE);
           q.setMaxResults(1);
           return (ProfilePrivacy) q.uniqueResult();
     };

	return getHibernateTemplate().execute(hcb);
}
 
Example 12
Source File: ProfileDaoImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
	 * {@inheritDoc}
	 */
@Override
public Message getMessage(final String id) {
	
	final HibernateCallback<Message> hcb = session -> {
           final Query q = session.getNamedQuery(QUERY_GET_MESSAGE);
           q.setParameter(ID, id, StringType.INSTANCE);
           q.setMaxResults(1);
           return (Message) q.uniqueResult();
     };

	return getHibernateTemplate().execute(hcb);
}
 
Example 13
Source File: ProfileDaoImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
	 * {@inheritDoc}
	 */
@Override
public ProfileImageOfficial getOfficialImageRecordForUser(final String userUuid) {
	
	final HibernateCallback<ProfileImageOfficial> hcb = session -> {
           final Query q = session.getNamedQuery(QUERY_GET_OFFICIAL_IMAGE_RECORD);
           q.setParameter(USER_UUID, userUuid, StringType.INSTANCE);
           q.setMaxResults(1);
           return (ProfileImageOfficial) q.uniqueResult();
     };

	return getHibernateTemplate().execute(hcb);
}
 
Example 14
Source File: ProfileDaoImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
	 * {@inheritDoc}
	 */
@Override
public MessageParticipant getMessageParticipant(final String messageId, final String userUuid) {
	
	final HibernateCallback<MessageParticipant> hcb = session -> {
           final Query q = session.getNamedQuery(QUERY_GET_MESSAGE_PARTICIPANT_FOR_MESSAGE_AND_UUID);
           q.setParameter(MESSAGE_ID, messageId, StringType.INSTANCE);
           q.setParameter(UUID, userUuid, StringType.INSTANCE);
           q.setMaxResults(1);
           return (MessageParticipant) q.uniqueResult();
     };

	return getHibernateTemplate().execute(hcb);
}
 
Example 15
Source File: ProfileDaoImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
	 * {@inheritDoc}
	 */
@Override
public ProfileImageExternal getExternalImageRecordForUser(final String userId) {
	
	final HibernateCallback<ProfileImageExternal> hcb = session -> {
           final Query q = session.getNamedQuery(QUERY_GET_EXTERNAL_IMAGE_RECORD);
           q.setParameter(USER_UUID, userId, StringType.INSTANCE);
           q.setMaxResults(1);
           return (ProfileImageExternal) q.uniqueResult();
     };

	return getHibernateTemplate().execute(hcb);
}
 
Example 16
Source File: ProfileDaoImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
	 * {@inheritDoc}
	 */
@Override
public Message getMessage(final String id) {
	
	final HibernateCallback<Message> hcb = session -> {
           final Query q = session.getNamedQuery(QUERY_GET_MESSAGE);
           q.setParameter(ID, id, StringType.INSTANCE);
           q.setMaxResults(1);
           return (Message) q.uniqueResult();
     };

	return getHibernateTemplate().execute(hcb);
}
 
Example 17
Source File: TransformerImpl.java    From robe with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public Result<E> pairList(Criteria<E> criteria) {
    Result<E> result  = new Result<>();
    BooleanHolder groupBy = new BooleanHolder(false);
    TransformerUtil.Elements elements = new TransformerUtil.Elements();
    Pair<String, Pair<String, Map<String, Object>>> pair = TransformerUtil.pairList(criteria, elements, groupBy);
    Query listQuery = session.createQuery(pair.getLeft());
    if(elements.elementsMap != null && elements.elementsMap.size() > 0) {

    }
    if(criteria.getLimit() != null) {
        listQuery.setMaxResults(criteria.getLimit());
    }
    if(criteria.getOffset() != null) {
        listQuery.setFirstResult(criteria.getOffset());
    }
    setResultTransformer(listQuery);
    Query countQuery = session.createQuery(pair.getRight().getLeft());
    for(Map.Entry<String, Object> parameter: pair.getRight().getRight().entrySet()) {
        setParameter(listQuery, parameter.getKey(), parameter.getValue());
        setParameter(countQuery, parameter.getKey(), parameter.getValue());
    }
    List<E> destinationList = listQuery.list();
    setElementsToList(criteria, pair.getRight().getRight(), elements, destinationList);
    result.setList(destinationList);
    result.setTotalCount(groupBy.is() ? countQuery.list().size(): (long)countQuery.uniqueResult());
    return result;
}
 
Example 18
Source File: HibernateDao.java    From DataHubSystem with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * <p>Returns a List of <b>T</b> entities, where HQL clauses can be
 * specified.</p>
 * 
 * Note: This method is useful in read only. It can be use to delete or 
 * create <b>T</b> entities, but caution with <code>top</code> and 
 * <code>skip</code> arguments.
 * 
 * @param clauses query clauses (WHERE, ORDER BY, GROUP BY), if null no
 * clauses are apply.
 * @param skip number of entities to skip.
 * @param n  number of entities max returned.
 * @return a list of <b>T</b> entities.
 */
@SuppressWarnings ("unchecked")
public List<T> scroll (final String clauses, final int skip, final int n)
{
   StringBuilder hql = new StringBuilder ();
   hql.append ("FROM ").append (entityClass.getName ());
   if (clauses != null)
      hql.append (" ").append (clauses);

   Session session;
   boolean newSession = false;
   try
   {
      session = getSessionFactory ().getCurrentSession ();
   }
   catch (HibernateException e)
   {
      session = getSessionFactory ().openSession ();
      newSession = true;
   }

   Query query = session.createQuery (hql.toString ());
   if (skip > 0) query.setFirstResult (skip);
   if (n > 0) 
   {
      query.setMaxResults (n);
      query.setFetchSize (n);
   }
   
   logger.info("Execution of HQL: " + hql.toString ());
   long start = System.currentTimeMillis ();

   List<T> result = (List<T>) query.list ();
   logger.info("HQL executed in " + 
      (System.currentTimeMillis() -start) + "ms.");

   if (newSession)
   {
      session.disconnect ();
   }

   return result;
}
 
Example 19
Source File: StatisticsReportingStorage.java    From sailfish-core with Apache License 2.0 3 votes vote down vote up
@SuppressWarnings("unchecked")
public List<TestCaseHistoryRow> generateTestCaseHistoryReport(AggregateReportParameters params) {

       String queryString = "select new com.exactpro.sf.embedded.statistics.storage.TestCaseHistoryRow(TC.testCaseId, M.name, TCR.startTime, TCR.finishTime, TCR.status, TCR.failReason) "
			+ "from TestCaseRun as TCR "
			+ "join TCR.testCase as TC "
			+ "join TCR.matrixRun as MR "
			+ "join MR.matrix AS M "
			+ "where TC.id = :tcId "
			+ "order by TCR.startTime, TCR.id";

	Session session = null;

	try {

           session = sessionFactory.openSession();
		Query query = session.createQuery(queryString);

		query.setParameter("tcId", params.getTestCaseId());

		query.setMaxResults(10);

		return query.list();

	} finally {

		if(session != null) {
			session.close();
		}

	}

}
 
Example 20
Source File: DatabaseMessageStorage.java    From sailfish-core with Apache License 2.0 2 votes vote down vote up
@Override
public List<MessageRow> getMessages(int offset, int count, String where) {
	Session session = null;

	flusher.flush();

	try {
		if(count == 0) {
			return new ArrayList<>();
		}

           session = sessionFactory.openSession();

		String strQuery = "from StoredMessage msg ";

           if(!where.isEmpty()) {
               strQuery += " where " + where;
           }
		strQuery += " order by msg.id desc ";

		Query query = session.createQuery(strQuery);

		logger.debug("query: {}", query.getQueryString());

		query.setFirstResult(offset);

           if(count != -1) {
               query.setMaxResults(count);
           }

		List<MessageRow> result = new ArrayList<>();

           @SuppressWarnings("unchecked")
           List<StoredMessage> resultList = query.list();

		session.close();

           for(int i = 0; i < resultList.size(); i++) {
               result.add(convert(resultList.get(i), interner, true));
		}

		return result;

	} catch (RuntimeException e) {

		logger.error("Could not retrieve messages", e);
		throw new StorageException("Could not retrieve messages", e);

	} finally {
		if (session != null && session.isOpen()) {
			session.close();
		}
	}

}