Hibernate系列之----Query接口


public void testQuery(){
		Session session = null;
		try{
			session = HibernateUtils.getSession();
			session.beginTransaction();
			
			Query query = session.createQuery("from User");
			List userList = query.list();
			for(Iterator iter = userList.iterator(); iter.hasNext();)
			{
				User user = (User) iter.next();
				System.out.println(user.getId());
				System.out.println(user.getName());
			}
			
			session.getTransaction().commit();
		}catch (Exception e) {
			session.getTransaction().rollback();
		}finally{
			HibernateUtils.closeSession(session);
		}
	}

结果:
Hibernate: select user0_.id as id0_, user0_.name as name0_, user0_.password as password0_, user0_.createTime as createTime0_, user0_.expireTime as expireTime0_ from User user0_
4028818238e29fd10138e29fd4210000
李四
4028818238e2a3f00138e2a3f19b0000
王五
4028818238e2a4410138e2a442220000
王五
4028818238e2a64c0138e2a64da80000
李四
4028818238e2ad180138e2ad19680000
张三




public void testQuery(){
		Session session = null;
		try{
			session = HibernateUtils.getSession();
			session.beginTransaction();
			
			Query query = session.createQuery("from User");
			
			/*分页*/
			query.setFirstResult(0);
			query.setMaxResults(2);
			
			List userList = query.list();
			for(Iterator iter = userList.iterator(); iter.hasNext();)
			{
				User user = (User) iter.next();
				System.out.println(user.getId());
				System.out.println(user.getName());
			}
			
			session.getTransaction().commit();
		}catch (Exception e) {
			session.getTransaction().rollback();
		}finally{
			HibernateUtils.closeSession(session);
		}
	}

结果:

Hibernate: select user0_.id as id0_, user0_.name as name0_, user0_.password as password0_, user0_.createTime as createTime0_, user0_.expireTime as expireTime0_ from User user0_ limit ?
4028818238e29fd10138e29fd4210000
李四
4028818238e2a3f00138e2a3f19b0000
王五



你可能感兴趣的:(Hibernate,exception,session,user,iterator,query)