首页 > 代码库 > Hibernate中使用HQLQuery查询全部数据和部分数据

Hibernate中使用HQLQuery查询全部数据和部分数据

package com.lc.view;

import java.util.Iterator;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;

import com.lc.domain.Student;
import com.lc.utils.HibernateUtil;

public class selectStudent {

	public static void main(String[] args) {
		selectSomeStudents();
	}
	/*
	 * 1.检索所有的学生
	 */
	public static void selectAllStudents(){
		Session session = null;
		Transaction ts = null;
		try {
			session = HibernateUtil.getCurrentSession();
			ts = session.beginTransaction();
			
			List<Student> list = session.createQuery("from Student").list();
			//取出数据1.for循环增强
			for(Student stu:list){
				System.out.println(stu.getSid()+" "+ stu.getSname()+"  "+stu.getSdept());
			}
			//取出数据2.迭代器
			System.out.println("------------------------------");
			Iterator iterator = list.iterator();
			while(iterator.hasNext()){
				Student s = (Student) iterator.next();
				System.out.println(s.getSid()+" "+ s.getSname()+"  "+s.getSdept());
			}
			
			ts.commit();
		} catch (Exception e) {
			if (ts != null) {
				ts.rollback();
			}
			throw new RuntimeException(e.getMessage());
		} finally {
			if (session != null && session.isOpen()) {
				session.close();
			}
		}
	}
	/*
	 * 2.检索部分的学生
	 */
	public static void selectSomeStudents(){
		Session session = null;
		Transaction ts = null;
		try {
			session = HibernateUtil.getCurrentSession();
			ts = session.beginTransaction();
			
			/*
			 *不可以这样去除数据了  因为只有Student对象的两个属性值 不是一个对象 
			List<Student> list = session.createQuery("select sname,sdept from Student").list();
			for(Student stu:list){
				System.out.println(stu.getSname()+" "+stu.getSdept());
			}*/
			
			List list = session.createQuery("select sname,sdept from Student").list();
			for(int i=0;i<list.size();i++){
				Object[] obj = (Object[]) list.get(i);
				System.out.println(obj[0].toString()+" "+obj[1].toString());
			}
			
			ts.commit();
		} catch (Exception e) {
			if (ts != null) {
				ts.rollback();
			}
			throw new RuntimeException(e.getMessage());
		} finally {
			if (session != null && session.isOpen()) {
				session.close();
			}
		}
	}
}


Hibernate中使用HQLQuery查询全部数据和部分数据