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

The following are Jave code examples for showing how to use list() 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.
+ Save this method
Example 1
Project: Hibernate_Association_Mapping_ManyToOne_Save_Load_Maven   File: MTO_DAOImpl.java   View Source Code Vote up 8 votes
@Override
public void loadDataUsingParent() {
	Session ses=null;
	Query query=null;
	List<Department> list=null;
	List<Employee> emplist=null;
	
	//get Session
	ses=HibernateUtil.getSession();
	//create Query obj
	query=ses.createQuery("from Employee");
	//execute Query
	emplist=query.list();
	//process the Results
	for(Employee emp:emplist){
		System.out.println("Child---->"+emp);
		//get all childs of each parent
			Department dept=emp.getDept();
			System.out.println("Parent--->"+dept);
		/*for(PhoneNumber ph:childs){
			
		}//for
	*/
		}//for
}
 
Example 2
Project: lams   File: AssessmentUserDAOHibernate.java   View Source Code Vote up 6 votes
@SuppressWarnings("rawtypes")
   @Override
   public Object[] getStatsMarksForLeaders(Long toolContentId) {

Query query = getSession().createSQLQuery(FIND_MARK_STATS_FOR_LEADERS)
	.addScalar("min_grade", FloatType.INSTANCE)
	.addScalar("avg_grade", FloatType.INSTANCE)
	.addScalar("max_grade", FloatType.INSTANCE)
	.addScalar("num_complete", IntegerType.INSTANCE);
query.setLong("toolContentId", toolContentId);
List list = query.list();
if ((list == null) || (list.size() == 0)) {
    return null;
} else {
    return (Object[]) list.get(0);
}
   }
 
Example 3
Project: dhus-core   File: HibernateDao.java   View Source Code Vote up 6 votes
@SuppressWarnings("unchecked")
public List<T> executeHQLQuery(final String hql,
      final List<SQLVisitor.SQLVisitorParameter> parameters,
      final int skip, final int top)
{
   Session session = getSessionFactory().getCurrentSession();
   Query query = session.createQuery(hql);
   for (int i = 0; i < parameters.size(); i++)
   {
      SQLVisitor.SQLVisitorParameter param = parameters.get(i);
      query.setParameter(i, param.getValue(), param.getType());
   }

   if (skip > -1)
   {
      query.setFirstResult(skip);
   }
   if (top > -1)
   {
      query.setMaxResults(top);
   }
   query.setReadOnly(true);
   return (List<T>) query.list();
}
 
Example 4
Project: unitimes   File: ChangeLog.java   View Source Code Vote up 6 votes
public static List findLastNChanges(Object object, Source source, int n) {
    try {
        Number objectUniqueId = (Number)object.getClass().getMethod("getUniqueId", new Class[]{}).invoke(object, new Object[]{});
        String objectType = object.getClass().getName();
        org.hibernate.Session hibSession = new ChangeLogDAO().getSession(); 
        Query q = hibSession.createQuery(
                    "select ch from ChangeLog ch " +
                    "where ch.objectUniqueId=:objectUniqueId and ch.objectType=:objectType "+
                    (source==null?"":"and ch.sourceString=:source ") +
                    "order by ch.timeStamp desc");
        q.setLong("objectUniqueId", objectUniqueId.longValue());
        q.setString("objectType",objectType);
        if (source!=null)
            q.setString("source",source.name());
        q.setMaxResults(n);
        q.setCacheable(true);
        return q.list();
    } catch (Exception e) {
        Debug.error(e);
    }
    return null;
}
 
Example 5
Project: ImageClassify   File: TaskService.java   View Source Code 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 6
Project: hibernateMaster   File: DaoUtil.java   View Source Code Vote up 6 votes
/**
 * 随机取size条记录
 * 
 * @param <T> 要查询的实体类
 * 
 * @param target 要查询的实体类
 * @param size 记录数
 * @param where 查询条件
 * 
 * @return 查询到的记录
 */
@SuppressWarnings("unchecked")
public final static <T> List<T> randomlistObj(Class<T> target,int size,Map<String, Object> where){
	try {
		List<String> randList = new ArrayList<String>(1);
		randList.add("RAND()");
		StringBuffer hql = getSelectHql(target, where, null, null);
		hql.append(" order by RAND()");
		Query query = createQuery(where,hql);
		faging(size,1, query);
		return query.list();
	} catch (Exception e) {
		setException(e);
		return null;
	}finally{
		closeSession();
	}
}
 
Example 7
Project: Celebino   File: GenericDao.java   View Source Code Vote up 6 votes
public List<T> getAll(String namedQuery) throws SQLException {
	logger.info("Init abstract GetAll to: " + namedQuery);

	Session session = HibernateUtil.getSessionFactory().openSession();
	List<T> list = null;

	try {
		session.beginTransaction();
		Query query = session.getNamedQuery(namedQuery);
		list = (List<T>) query.list();
		session.getTransaction().commit();

	} catch (HibernateException hibernateException) {
		session.getTransaction().rollback();

		throw new SQLException(hibernateException);

	} finally {
		session.close();
	}

	return list;
}
 
Example 8
Project: training-sample   File: HibernateUserDao.java   View Source Code Vote up 6 votes
@SuppressWarnings("unchecked")
@Override
public List<User> findByExample(User user) {
	List<User> users = null;
	Session session = sessionFactory.getCurrentSession();
	try {
		session.beginTransaction();
		Query query = session.createQuery("from User where name=:name and age=:age");
		query.setProperties(user);
		query.setProperties(user);
		users = (List<User>) query.list();
		session.getTransaction().commit();
	} catch (RuntimeException e) {
		session.getTransaction().rollback();
	}
	return users;
}
 
Example 9
Project: SchTtableServer   File: StatusDaoImpl.java   View Source Code Vote up 6 votes
@Override
public StatusBean get(String id) {
    if (id == null) {
        return null;
    }
    
    String hql = "FROM StatusBean WHERE id = :id";
    
    Session session = sessionFactory.getCurrentSession();
    Query query = session.createQuery(hql);
    query.setString("id", id);
    List list = query.list();
    if (list != null && !list.isEmpty()) {
        return (StatusBean) list.get(0);
    }
    return null;
}
 
Example 10
Project: DWSurvey   File: HibernateDao.java   View Source Code Vote up 6 votes
@Override
public Page<T> findPage(final PageRequest pageRequest, String hql, final Object... values) {
	AssertUtils.notNull(pageRequest, "pageRequest不能为空");

	Page<T> page = new Page<T>(pageRequest);

	if (pageRequest.isCountTotal()) {
		long totalCount = countHqlResult(hql, values);
		page.setTotalItems(totalCount);
	}

	if (pageRequest.isOrderBySetted()) {
		hql = setOrderParameterToHql(hql, pageRequest);
	}
	Query q = createQuery(hql, values);

	setPageParameterToQuery(q, pageRequest);

	List result = q.list();
	page.setResult(result);
	return page;
}
 
Example 11
Project: ImageClassify   File: TaskService.java   View Source Code Vote up 6 votes
/**
 * 获取user_id对应的已提交的Task
 */
@Override
public List<Task> geTasksOfUnconfirmed(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 = 1 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 12
Project: unitimes   File: Staff.java   View Source Code Vote up 5 votes
/**
 * 
 * @param deptCode
 * @return
 */
public static List getStaffByDept(String deptCode, Long acadSessionId) throws Exception {	
	if (deptCode == null){
		return(null);
	}
	
	Query q = StaffDAO.getInstance().getSession().createQuery(
			"select distinct s from Staff s where s.dept=:deptCode and " +
			"(select di.externalUniqueId from DepartmentalInstructor di " +
			"where di.department.deptCode=:deptCode and di.department.session.uniqueId=:sessionId and di.externalUniqueId = s.externalUniqueId ) is null");
	q.setString("deptCode", deptCode);
	q.setLong("sessionId", acadSessionId);
	q.setCacheable(true);
	return (q.list());
}
 
Example 13
Project: lams   File: LessonDAO.java   View Source Code Vote up 5 votes
@Override
   @SuppressWarnings("unchecked")
   public List<Long> getPreviewLessons(Integer limit) {
Query query = getSession().createQuery(FIND_PREVIEW_LESSON_IDS);
if (limit != null) {
    query.setMaxResults(limit);
}
return query.list();
   }
 
Example 14
Project: baozijuan.com   File: BaseDaoHibernate.java   View Source Code Vote up 5 votes
@SuppressWarnings("unchecked")
protected List<T> find(String hql, Object... params) {
	Query query = getSessionFactory().getCurrentSession().createQuery(hql);
	for (int i = 0, len = params.length; i < len; i++) {
		query.setParameter(i + "", params[i]);
	}
	return query.list();
}
 
Example 15
Project: sdudoc   File: UserDaoImpl.java   View Source Code Vote up 5 votes
@Override
public User getUserByName$Pw(String username, String password) {
	String sql = "from User where username=:username and password=:password";
	Session session = sessionFactory.getCurrentSession();
	Query query = session.createQuery(sql);
	query.setString("username", username);
	query.setString("password", password);
	List<User> users = query.list();
	if(users.size() == 0) {
		return null;
	}
	return users.get(0);
}
 
Example 16
Project: unitimes   File: LookupTables.java   View Source Code Vote up 5 votes
/**
   * Executes the query to retrieve instructors
   * @param request
   * @param clause
   * @throws Exception
   */
  private static void getInstructors(HttpServletRequest request, SessionContext context, StringBuffer clause) throws Exception {
      String instructorNameFormat = UserProperty.NameFormat.get(context.getUser());
      
      Long acadSessionId = context.getUser().getCurrentAcademicSessionId();

StringBuffer query = new StringBuffer();
query.append("select distinct i from DepartmentalInstructor i ");
query.append(" where i.department.session.uniqueId = :acadSessionId ");
query.append(clause);
      query.append(" order by upper(i.lastName), upper(i.firstName) ");
      
      DepartmentalInstructorDAO idao = new DepartmentalInstructorDAO();
org.hibernate.Session hibSession = idao.getSession();

Query q = hibSession.createQuery(query.toString());
q.setFetchSize(5000);
q.setCacheable(true);
q.setLong("acadSessionId", acadSessionId);
      
List result = q.list();
      Vector v = new Vector(result.size());
      Vector h = new Vector(result.size());
   for (Iterator i=result.iterator();i.hasNext();) {
          DepartmentalInstructor di = (DepartmentalInstructor)i.next();
          String name = di.getName(instructorNameFormat);
          v.addElement(new ComboBoxLookup(name, di.getUniqueId().toString()));
          if (di.hasPreferences())
              h.add(di.getUniqueId());
}
      
      request.setAttribute(DepartmentalInstructor.INSTR_LIST_ATTR_NAME, v);
      request.setAttribute(DepartmentalInstructor.INSTR_HAS_PREF_ATTR_NAME, h);
  }
 
Example 17
Project: ImageClassify   File: MarkService.java   View Source Code 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 18
Project: unitimes   File: DistributionPref.java   View Source Code Vote up 4 votes
public static Collection getInstructorPreferences(Long sessionId, Long ownerId, Long subjectAreaId, String courseNbr) {
    if (sessionId==null) return null;
    StringBuffer sb = new StringBuffer();
    sb.append("select distinct dp ");
    sb.append(" from ");
    sb.append(" DistributionPref as dp, ");
    sb.append(" DepartmentalInstructor as di ");
    if (subjectAreaId!=null) {
        sb.append(" inner join di.classes as ci inner join ci.classInstructing.schedulingSubpart.instrOfferingConfig.instructionalOffering.courseOfferings as co ");
    }
    sb.append("where ");
    sb.append(" dp.owner = di ");
    sb.append(" and di.department.session.uniqueId = :sessionId ");
    if (subjectAreaId!=null) {
        sb.append(" and ci.lead = true ");
        sb.append(" and co.isControl = true ");
        sb.append(" and co.subjectArea.uniqueId = :subjectAreaId ");
        if (courseNbr!=null && courseNbr.trim().length()>0) {
            sb.append(" and co.courseNbr ");
            if (courseNbr.indexOf('*')>=0) {
                sb.append(" like ");
                courseNbr = courseNbr.replace('*', '%').toUpperCase();
            } else {
                sb.append(" = ");
            }
            sb.append(":courseNbr");
        }       
    } else if (ownerId != null) {
        sb.append(" and di.department.uniqueId = :ownerId ");
    }

    Query q = (new DistributionPrefDAO()).
        getSession().
        createQuery(sb.toString());
    q.setLong("sessionId", sessionId.longValue());
    if (subjectAreaId!=null) {
        q.setLong("subjectAreaId", subjectAreaId.longValue());
        if (courseNbr!=null && courseNbr.trim().length()>0)
            q.setString("courseNbr", courseNbr.toUpperCase());
    } else if (ownerId!=null) {
        q.setLong("ownerId", ownerId.longValue());
    }
    return q.list();
}
 
Example 19
Project: unitimes   File: DistributionPref.java   View Source Code Vote up 4 votes
public static Collection getPreferences(Long sessionId, Long ownerId, boolean useControllingCourseOfferingManager, Long uniqueId, Long subjectAreaId, String courseNbr) {
 	if (sessionId==null) return null;
 	StringBuffer sb = new StringBuffer();
 	sb.append("select distinct dp ");
 	sb.append(" from ");
 	sb.append(" DistributionPref as dp ");
 	sb.append(" inner join dp.distributionObjects as do, ");
 	sb.append(" Class_ as c ");
 	sb.append(" inner join c.schedulingSubpart as ss inner join ss.instrOfferingConfig.instructionalOffering as io ");
 	if(subjectAreaId != null || ownerId != null){
 		sb.append(" inner join io.courseOfferings as co ");
 	}
 	sb.append("where ");
 	sb.append(" (c.uniqueId = do.prefGroup.uniqueId or ss.uniqueId = do.prefGroup.uniqueId) and ");
 	sb.append(" io.session.uniqueId = :sessionId ");
 	if (ownerId != null){
 		sb.append(" and (");
 		sb.append("((c.managingDept is not null and c.managingDept.uniqueId = :ownerId )");
 		sb.append(" or (c.managingDept is null ");
 		sb.append(" and co.isControl = true ");
 		sb.append("and co.subjectArea.department.uniqueId = :ownerId))");
 		if (useControllingCourseOfferingManager)	{
 			sb.append(" or (co.isControl = true");
 			sb.append(" and co.subjectArea.department.uniqueId = :ownerId)");
 		}
 		sb.append(")");
 	}
 	if (uniqueId != null){
 		sb.append(" and (c.uniqueId = :uniqueId or ss.uniqueId = :uniqueId or io.uniqueId = :uniqueId))");
 	}
 	if(subjectAreaId != null){
 	    sb.append(" and co.subjectArea.uniqueId=:subjectAreaId ");
 	    
 		if (courseNbr!=null && courseNbr.trim().length()>0) {
 		    sb.append(" and co.courseNbr ");
 		    if (courseNbr.indexOf('*')>=0) {
 	            sb.append(" like ");
 	            courseNbr = courseNbr.replace('*', '%').toUpperCase();
 		    }
 		    else {
 	            sb.append(" = ");
 		    }
             sb.append(":courseNbr");
 		}		
 	}
	
 	Query q = (new DistributionPrefDAO()).
getSession().
createQuery(sb.toString());
 	q.setLong("sessionId", sessionId.longValue());
 	if (ownerId!=null)
 		q.setLong("ownerId", ownerId.longValue());
 	if (uniqueId!=null)
 		q.setLong("uniqueId", uniqueId.longValue());
 	if (subjectAreaId!=null) {
 		q.setLong("subjectAreaId", subjectAreaId.longValue());
 		if (courseNbr!=null && courseNbr.trim().length()>0)
 		    q.setString("courseNbr", courseNbr.toUpperCase());
 	}
 	return q.list();
 }
 
Example 20
Project: Library   File: LibraryServicesImpl.java   View Source Code Vote up 3 votes
public List<Fine> getFineForCardId(SearchQuery searchQuery) {

	
	boolean isPaid = Boolean.parseBoolean(searchQuery.getPaid());
	
	System.out.println("Ispaid " + isPaid);
	Session session = this.sessionFactory.openSession();
	String param = "from BookLoan where borrower.cardId="+ Integer.parseInt(searchQuery.getQuery());
			
	Query query = session.createQuery(param);
	
	List<BookLoan> bookLoans = query.list();
	
	List<Fine> fines = new ArrayList<Fine>();
	
	
	for(BookLoan bookLoan :bookLoans){
		if(bookLoan.getFine()!=null){
			if(isPaid && bookLoan.getFine().isPaid()){
				fines.add(bookLoan.getFine());
			}
			if(!isPaid && !bookLoan.getFine().isPaid()){
				fines.add(bookLoan.getFine());
			}
		}			
	}
	
	session.close();
	
	return fines;
}