Java Code Examples for org.hibernate.Query.setFirstResult()

The following are Jave code examples for showing how to use setFirstResult() of the org.hibernate.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: ImageClassify   File: AdminService.java   Source Code and License Vote up 6 votes
@Override
public List<User> getAllUsers(int start,int num) { 
	 List<User> users = new ArrayList<User>();
        Session session = HibernateUtils.getSession();//生成Session实例
	 Transaction tx = session.beginTransaction();//生成事务实例 
	 
	 try {
		  Query query = session.createQuery("select new User(user_id,username,tel_num,integral,accuracy,is_frozen) from User order by user_id");
		  query.setFirstResult(start-1);
		  System.out.println(start-1);
		  System.out.println(num);
		  query.setMaxResults(num);
		  users = query.list();
		 tx.commit();//提交事务
	} catch (Exception e) {
		e.printStackTrace();
		tx.rollback();
	}finally {
		HibernateUtils.closeSession();//关闭session实例
	}
	 return users;  
}
 
Example 2
Project: jeesupport   File: AbsSupportDao.java   Source Code and License Vote up 6 votes
@Override
@SuppressWarnings( "unchecked" )
public < T > List< T > selectBySQL( String _db , String _sql , int _first , int _limit , Object[] _param ,
				Class< T > _cls ) {
	Session sess = _get_session( _db );
	Query query = sess.createSQLQuery( _sql );
	query.setFirstResult( _first );
	query.setMaxResults( _limit );
	int i = 0;
	if ( _param != null ) for ( Object o : _param )
		query.setParameter( i++ , o );
	return query.list();
}
 
Example 3
Project: lams   File: LessonDAO.java   Source Code and License Vote up 6 votes
@SuppressWarnings("unchecked")
   @Override
   public List<User> getLearnersByLesson(Long lessonId, String searchPhrase, Integer limit, Integer offset,
    boolean orderAscending) {
StringBuilder queryTextBuilder = new StringBuilder("SELECT users ").append(LessonDAO.LOAD_LEARNERS_BY_LESSON);
if (!StringUtils.isBlank(searchPhrase)) {
    String[] tokens = searchPhrase.trim().split("\\s+");
    for (String token : tokens) {
	token = StringEscapeUtils.escapeSql(token).replace("\\", "\\\\");
	queryTextBuilder.append(" AND (users.firstName LIKE '%").append(token)
		.append("%' OR users.lastName LIKE '%").append(token).append("%' OR users.login LIKE '%")
		.append(token).append("%')");
    }
}
String order = orderAscending ? "ASC" : "DESC";
queryTextBuilder.append(" ORDER BY users.firstName ").append(order).append(", users.lastName ").append(order)
	.append(", users.login ").append(order);
Query query = getSession().createQuery(queryTextBuilder.toString()).setLong("lessonId", lessonId);
if (limit != null) {
    query.setMaxResults(limit);
}
if (offset != null) {
    query.setFirstResult(offset);
}
return query.list();
   }
 
Example 4
Project: ImageClassify   File: TaskService.java   Source Code and License Vote up 6 votes
/**
 * 获取该用户未提交或者未完成的任务
 */
@Override
public List<Task> geTasksOfUnfinished(int user_id,int start,int num) { 
	List<Task> tasks = new ArrayList<Task>();  
	Session session = HibernateUtils.getSession();//生成Session实例
	 Transaction tx = session.beginTransaction();//生成事务实例
	 try {
		 Query query =  session.createQuery("SELECT  new Task( task_id,task_img_amount,task_start_time,user_id) FROM Task WHERE task_iscommit = 0 AND user_id = "+user_id);
		 query.setFirstResult(start-1);
		 query.setMaxResults(num);
		 tasks = query.list();
	     tx.commit();//提交事务
	} catch (Exception e) {
		e.printStackTrace();
		tx.rollback();//事务回滚
	}finally{
		HibernateUtils.closeSession();//关闭session实例
	}
	 return tasks;  
}
 
Example 5
Project: jshERP   File: BaseDAO.java   Source Code and License Vote up 6 votes
@SuppressWarnings("unchecked")
@Override
public void find(PageUtil<T> pageUtil) throws DataAccessException
{
	Query query = this.getHibernateTemplate().getSessionFactory().getCurrentSession()
			.createQuery(" from " + getEntityClass().getName() + " where 1=1 "+
					SearchConditionUtil.getCondition(pageUtil.getAdvSearch()));
	pageUtil.setTotalCount(query.list().size());

	// 分页查询
	int pageNo = pageUtil.getCurPage();
	int pageSize = pageUtil.getPageSize();
	if (0 != pageNo && 0 != pageSize)
	{
		query.setFirstResult((pageNo - 1) * pageSize);
		query.setMaxResults(pageSize);
	}
	pageUtil.setPageList(query.list());
}
 
Example 6
Project: jshERP   File: BaseDAO.java   Source Code and License Vote up 5 votes
@SuppressWarnings("unchecked")
@Override
public List<T> find(Map<String, Object> conditon, int pageSize, int pageNo)throws DataAccessException
{
	Query query = this.getHibernateTemplate().getSessionFactory().getCurrentSession()
			.createQuery(" from " + getEntityClass().getName() + " where 1=1 "+ SearchConditionUtil.getCondition(conditon));
	query.setFirstResult((pageNo - 1) * pageSize);
	query.setMaxResults(pageSize);
	return query.list();
}
 
Example 7
Project: ImageClassify   File: CompositionService.java   Source Code and License Vote up 5 votes
/**
 * 获取总任务量排行
 */
@Override
public List<UserRank> getRankListOfAmountTask(int start, int num) {
	// String sqlOfAmountOfTask = "";
	 List<UserRank> amountOfTasks = new ArrayList<UserRank>();
	 Session session = HibernateUtils.getSession();//生成Session实例
	 Transaction tx = session.beginTransaction();//生成事务实例 
	 String sql = "SELECT username,sex,avatar_url,COUNT(*) AS amount FROM task LEFT JOIN USER ON user.user_id = task.user_id WHERE task.task_iscommit = 1 GROUP BY task.user_id ORDER BY amount DESC";
	  
	 try { 
		 Query query = session.createSQLQuery(sql); 
		 query.setFirstResult(start-1);
		 query.setMaxResults(num);
		 amountOfTasks = query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list();
	     //调用session的get()方法,找到此用户到内存中
	    tx.commit();//提交事务
	} catch (Exception e) {
		e.printStackTrace();
		tx.rollback();//事务回滚
	}finally{
		HibernateUtils.closeSession();//关闭session实例
	}     
	 List<UserRank> amountOfTasks2 = new ArrayList<UserRank>(); 
	 
	 for (int i = 0; i < amountOfTasks.size(); i++) { 
		 UserRank amountOfTask = new UserRank();
		  Map map = (Map) amountOfTasks.get(i); 
		  amountOfTask.setUsername(map.get("username")+""); 
		  amountOfTask.setSex(map.get("sex")+"");
		  amountOfTask.setAvatar_url(map.get("avatar_url")+"");
		  amountOfTask.setAmount(map.get("amount")+"");
		  amountOfTask.setIntegral("");
		  amountOfTask.setAccuracy("");
		  amountOfTasks2.add(amountOfTask);
	 }  
	 return amountOfTasks2; 
}
 
Example 8
Project: lams   File: LearnerProgressDAO.java   Source Code and License Vote up 5 votes
@SuppressWarnings("unchecked")
   @Override
   public List<User> getLearnersLatestByActivity(Long activityId, Integer limit, Integer offset) {
Query query = getSession().createSQLQuery(LearnerProgressDAO.LOAD_LEARNERS_LATEST_BY_ACTIVITY)
	.addEntity(User.class).setLong("activityId", activityId);
if (limit != null) {
    query.setMaxResults(limit);
}
if (offset != null) {
    query.setFirstResult(offset);
}
return query.list();
   }
 
Example 9
Project: lams   File: EventDAOHibernate.java   Source Code and License Vote up 5 votes
@Override
   @SuppressWarnings("unchecked")
   public List<User> getArchivedEmailNotificationRecipients(Long emailNotificationUid, Integer limit, Integer offset) {
Query queryObject = getSession().createQuery(EventDAOHibernate.GET_ARCHIVED_EMAIL_NOTIFICATION_RECIPIENTS);
queryObject.setLong(0, emailNotificationUid);
if (limit != null) {
    queryObject.setMaxResults(limit);
}
if (offset != null) {
    queryObject.setFirstResult(offset);
}
return queryObject.list();
   }
 
Example 10
Project: djpt   File: DaoImpl.java   Source Code and License Vote up 5 votes
public <T> List<T> findByHql(String hql, Object[] vals, int from_id, int len) {
	Session session = hibernateTemplate.getSessionFactory().openSession();
	org.hibernate.Transaction tx = session.beginTransaction(); 
	
	Query query = session.createQuery(hql);
	if(vals != null) {
		for(int i=0;i<vals.length;i++) {
			if(vals[i] instanceof Integer) {
				query.setInteger(i, (Integer)vals[i]);
			} else {
				query.setString(i, vals[i].toString());
			}
		}
	}
	
	if(len>0) {
		query.setFirstResult(from_id);
		query.setMaxResults(len);
	}
	
	try {
		tx.commit();
		return query.list();
	} catch (Exception e) {
		e.printStackTrace();
		tx.rollback();
		return null;
	} finally {
		session.close(); 
	}
	
}
 
Example 11
Project: jeesupport   File: AbsSupportDao.java   Source Code and License Vote up 5 votes
@Override
@SuppressWarnings( "unchecked" )
public < T > List< T > selectByHQL( String _db , String _hql , int _first , int _limit , Object[] _param ,
				Class< T > _cls ) {
	Session sess = _get_session( _db );
	Query query = sess.createQuery( _hql );
	query.setFirstResult( _first );
	query.setMaxResults( _limit );
	int i = 0;
	if ( _param != null ) for ( Object o : _param )
		query.setParameter( i++ , o );
	return query.list();
}
 
Example 12
Project: ImageClassify   File: MarkService.java   Source Code and License Vote up 5 votes
@Override
public List<Image_Mark> getComposition(int amount,int user_id) {
	 List<Image_Mark> marks = new ArrayList<Image_Mark>();
	 Session session = HibernateUtils.getSession();//生成Session实例
	 Transaction tx = session.beginTransaction();//生成事务实例
	 
	 try { 
	    Query query = session.createSQLQuery("SELECT img_machine_tag_label,img_path,img_name,user_id,img_id FROM image_mark GROUP BY img_id HAVING img_id NOT IN(SELECT img_id FROM Mark WHERE user_id = "+user_id+") ORDER BY COUNT(*) ASC")
	    		.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);  
		    query.setFirstResult(0);
		    query.setMaxResults(amount);
	    marks = query.list();
	     //调用session的get()方法,找到此用户到内存中
	    tx.commit();//提交事务
	} catch (Exception e) {
		e.printStackTrace();
		tx.rollback();//事务回滚
	}finally{
		HibernateUtils.closeSession();//关闭session实例
	} 
	 List<Image_Mark> marks2 = new ArrayList<Image_Mark>();
	 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	 
	 for (int i = 0; i < marks.size(); i++) { 
		 Image_Mark image_Mark = new Image_Mark();
		  Map map = (Map) marks.get(i);
		  //img_machine_tag_label,img_path,img_name,user_id,img_id
		  image_Mark.setImg_id(map.get("img_id")+"");
		  image_Mark.setImg_machine_tag_label(map.get("img_machine_tag_label")+"");
		  image_Mark.setImg_name(map.get("img_name")+"");
		  image_Mark.setImg_path(map.get("img_path")+"");
		   marks2.add(image_Mark);
	 }  
	 return marks2;
}
 
Example 13
Project: jshERP   File: BaseDAO.java   Source Code and License Vote up 5 votes
@SuppressWarnings("unchecked")
@Override
public List<T> find(String hql, int pageSize, int pageNo)throws DataAccessException
{
	Query query = this.getHibernateTemplate().getSessionFactory().getCurrentSession()
			.createQuery(" from " + getEntityClass().getName() + " where 1=1 "+ hql);
	query.setFirstResult((pageNo - 1) * pageSize);
	query.setMaxResults(pageSize);
	return query.list();
}
 
Example 14
Project: lams   File: OrganisationDAO.java   Source Code and License Vote up 5 votes
@SuppressWarnings("unchecked")
   @Override
   public List<Organisation> getPagedCourses(Integer parentOrgId, Integer typeId, Integer stateId, int page, int size,
    String sortBy, String sortOrder, String searchString) {
String sortByParam = "o.name";
switch (sortBy) {
    case "id":
	sortByParam = "o.organisationId";
	break;
    case "name":
	sortByParam = "o.name";
	break;
    case "code":
	sortByParam = "o.code";
	break;
    case "description":
	sortByParam = "o.createDate";
	break;
}

Query query = getSession().createQuery(OrganisationDAO.GET_PAGED_COURSES + sortByParam + " " + sortOrder);
query.setInteger("typeId", typeId);
query.setInteger("stateId", stateId);
query.setInteger("parentOrgId", parentOrgId);
// support for custom search from a toolbar
searchString = searchString == null ? "" : searchString;
query.setString("searchString", searchString);
query.setFirstResult(page * size);
query.setMaxResults(size);
return query.list();
   }
 
Example 15
Project: dhus-core   File: HibernateDao.java   Source Code and License Vote up 4 votes
/**
 * <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.
 * @deprecated use of {@link #listCriteria(DetachedCriteria, int, int)}
 */
@Deprecated
@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 16
Project: ImageClassify   File: MarkService.java   Source Code and License Vote up 4 votes
@Override
public List<Image_Composition> getCompositionOfAll(int amount, int user_id,String orderOfTime,String orderOfAmount) {
	 List<Image_Composition> marks = new ArrayList<Image_Composition>();
	 Session session = HibernateUtils.getSession();//生成Session实例
	 Transaction tx = session.beginTransaction();//生成事务实例
	 
	 ListToString listToString = new ListToString();
	 try { 
		  
		 String hql = "SELECT image_composition.img_id,image_composition.img_machine_tag_label,image_composition.img_path,image_composition.img_name "
		 		+ "FROM image_composition ,image WHERE image_composition.img_id = image.img_id AND image.img_is_finish <> 1";
		 
	     String hql1 = " AND  image_composition.img_id NOT IN";
	     String hql2 = "SELECT img_id FROM mark WHERE user_id = " +user_id;
	     String append = " ORDER BY image_composition.upload_time " + orderOfTime + ", image_composition.amount " + orderOfAmount;
		 List<Integer> imgIds = session.createSQLQuery(hql2).list();
		 
		 if (!imgIds.isEmpty()) {
			hql = hql + hql1 + listToString.getListToString(imgIds) + append;
		 } else {
			hql = hql + append;
		}
	    Query query = session.createSQLQuery(hql).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);  
		    query.setFirstResult(0);
		    query.setMaxResults(amount);
	    marks = query.list();
	     //调用session的get()方法,找到此用户到内存中
	    tx.commit();//提交事务
	} catch (Exception e) {
		e.printStackTrace();
		tx.rollback();//事务回滚
	}finally{
		HibernateUtils.closeSession();//关闭session实例
	} 
	 List<Image_Composition> marks2 = new ArrayList<Image_Composition>();
	 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	 
	 for (int i = 0; i < marks.size(); i++) { 
		 Image_Composition image_Composition = new Image_Composition();
		  Map map = (Map) marks.get(i);
		  //img_machine_tag_label,img_path,img_name,user_id,img_id
		  image_Composition.setImg_id(Integer.parseInt(map.get("img_id")+""));
		  image_Composition.setImg_machine_tag_label(map.get("img_machine_tag_label")+"");
		  image_Composition.setImg_name(map.get("img_name")+"");
		  image_Composition.setImg_path(map.get("img_path")+"");
		   marks2.add(image_Composition);
	 }  
	 return marks2; 
}
 
Example 17
Project: ImageClassify   File: CompositionService.java   Source Code and License Vote up 4 votes
@Override
public List<UserRank> getRankListOfAll(int start, int num,String rankidentification) {
	 List<UserRank> userRanks = new ArrayList<UserRank>();
	 Session session = HibernateUtils.getSession();//生成Session实例
	 Transaction tx = session.beginTransaction();//生成事务实例 
	 String sqlOfIntegral = "SELECT username,sex,integral,AVG(mark_accuracy) AS accuracy,avatar_url FROM USER LEFT JOIN image_mark ON user.user_id = image_mark.user_id  GROUP BY USER.user_id ORDER BY integral DESC";
	 String sqlOfAccuracy = "SELECT username,sex,integral,AVG(mark_accuracy) AS accuracy,avatar_url FROM USER LEFT JOIN image_mark ON user.user_id = image_mark.user_id  GROUP BY USER.user_id ORDER BY accuracy DESC";
	 String sql = "";
	 if (rankidentification.equals(Constant.INTEGRAL)) {
			sql = sqlOfIntegral;
	 }else if (rankidentification.equals(Constant.ACCURACY)) {
		 	sql = sqlOfAccuracy;
	 }
	 try { 
		 Query query = session.createSQLQuery(sql); 
		 query.setFirstResult(start-1);
		 query.setMaxResults(num);
		 userRanks = query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list();
	     //调用session的get()方法,找到此用户到内存中
	    tx.commit();//提交事务
	} catch (Exception e) {
		e.printStackTrace();
		tx.rollback();//事务回滚
	}finally{
		HibernateUtils.closeSession();//关闭session实例
	}     
	 List<UserRank> userRanks2 = new ArrayList<UserRank>(); 
	 
	 for (int i = 0; i < userRanks.size(); i++) { 
		  UserRank userRank = new UserRank();
		  Map map = (Map) userRanks.get(i); 
		  userRank.setUsername(map.get("username")+""); 
		  userRank.setSex(map.get("sex")+"");
		  userRank.setIntegral(map.get("integral")+"");
		  userRank.setAvatar_url(map.get("avatar_url")+"");
		  userRank.setAccuracy(map.get("accuracy")+""); 
		  userRank.setAmount("");
		  userRanks2.add(userRank);
	 }  
	 return userRanks2;  
}
 
Example 18
Project: lams   File: OrganisationDAO.java   Source Code and License Vote up 4 votes
@SuppressWarnings("unchecked")
   @Override
   public List<OrganisationDTO> getActiveCoursesByUser(Integer userId, boolean isSysadmin, int page, int size,
    String searchString) {

final String GET_ALL_ACTIVE_COURSE_IDS = "SELECT o.organisationId, o.name FROM Organisation o"
	+ " WHERE o.organisationType.organisationTypeId = " + OrganisationType.COURSE_TYPE
	+ " AND o.organisationState.organisationStateId = " + OrganisationState.ACTIVE
	+ " AND (o.name LIKE CONCAT('%', :searchString, '%')) ORDER BY o.name";

final String GET_ACTIVE_COURSE_IDS_BY_USER = "SELECT uo.organisation.organisationId, uo.organisation.name"
    + " FROM UserOrganisation uo "
    + " WHERE uo.organisation.organisationType.organisationTypeId = " + OrganisationType.COURSE_TYPE
    + " AND uo.organisation.organisationState.organisationStateId = " + OrganisationState.ACTIVE
    + " AND uo.user.userId = :userId "
    + " AND (uo.organisation.name LIKE CONCAT('%', :searchString, '%')) ORDER BY uo.organisation.name";

String queryStr = isSysadmin ? GET_ALL_ACTIVE_COURSE_IDS : GET_ACTIVE_COURSE_IDS_BY_USER;
Query query = getSession().createQuery(queryStr);
// support for custom search from a toolbar
searchString = searchString == null ? "" : searchString;
query.setString("searchString", searchString);
if (!isSysadmin) {
    query.setInteger("userId", userId);
}
query.setFirstResult(page * size);
query.setMaxResults(size);
List<Object[]> list = query.list();

List<OrganisationDTO> orgDtos = new ArrayList<OrganisationDTO>();
if (list != null && list.size() > 0) {
    for (Object[] element : list) {

	Integer orgId = ((Number) element[0]).intValue();
	String name = (String) element[1];

	OrganisationDTO orgDto = new OrganisationDTO(orgId, name);
	orgDtos.add(orgDto);
    }

}

return orgDtos;
   }
 
Example 19
Project: YiDu-Novel   File: HibernateSupportServiceImpl.java   Source Code and License Vote up 3 votes
/**
 * 根据hql,参数,指定区间获得List结果
 * 
 * @param hql
 *            hql
 * @param firstResult
 *            第一条结果
 * @param maxResults
 *            最大结果
 * @param params
 *            参数
 * @return List结果
 */
protected final <T> List<T> findByRange(final String hql, final int firstResult, final int maxResults,
        final Object... params) {
    Query query = this.getQuery(hql, params);
    query.setFirstResult(firstResult);
    query.setMaxResults(maxResults);
    return query.list();
}
 
Example 20
Project: Yidu   File: HibernateSupportServiceImpl.java   Source Code and License Vote up 3 votes
/**
 * 根据hql,参数,指定区间获得List结果
 * 
 * @param hql
 *            hql
 * @param firstResult
 *            第一条结果
 * @param maxResults
 *            最大结果
 * @param params
 *            参数
 * @return List结果
 */
protected final <T> List<T> findByRange(final String hql, final int firstResult, final int maxResults,
        final Object... params) {
    Query query = this.getQuery(hql, params);
    query.setFirstResult(firstResult);
    query.setMaxResults(maxResults);
    return query.list();
}