初始hibernate3.2—Query

Query用处查询:代码:

package cn.keith.hibernate;

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

import junit.framework.TestCase;

import org.hibernate.Query;
import org.hibernate.Session;

import cn.keith.hibernate.hibernateUtil.HibernateUtils;

public class StudentQueryTest extends TestCase {
	/***
	 * 查询全部内容
	 */
	public void testStudentQuery() {

		Session session = null;

		try {
			// 通过hibernate的工具类获得session
			session = HibernateUtils.getSession();
			// 开启事物
			session.beginTransaction();
			// from Student这个student不是表面,而是类名
			Query query = session.createQuery("from Student");
			// query返回值的类型是list,所以用List来接受
			List studentList = query.list();
			// 输出list值
			for (Iterator iter = studentList.iterator(); iter.hasNext();) {
				Student student = (Student) iter.next();
				System.out.println("student ID:" + student.getId() + "   "
						+ "student Name" + student.getName());
			}
			// 提交事物
			session.getTransaction().commit();
		} catch (Exception e) {
			e.printStackTrace();
			// 回滚事物
			session.getTransaction().rollback();
		} finally {
			// 关闭事物
			HibernateUtils.closeSession(session);
		}
	}

	/***
	 * 简单分页
	 */
	public void testStudentQuery1() {
		Session session = null;

		try {
			session = HibernateUtils.getSession();
			session.beginTransaction();
			Query query = session.createQuery("from Student");
			// 设置从那条数据开始
			query.setFirstResult(1);
			// 对多取多少条数据
			query.setMaxResults(2);
			//查询
			List studentList = query.list();
			//输出
			for (Iterator iter = studentList.iterator(); iter.hasNext();) {
				Student student = (Student) iter.next();
				System.out.println("student ID:" + student.getId() + "   "
						+ "student Name" + student.getName());
			}
			//提交事务
			session.getTransaction().commit();
		} catch (Exception e) {
			e.printStackTrace();
			//回滚事务
			session.getTransaction().rollback();
		} finally {
			//关闭session
			HibernateUtils.closeSession(session);
		}
	}
}

 

你可能感兴趣的:(Hibernate,JUnit)