首页 > 代码库 > hibernate之13.hql(二)

hibernate之13.hql(二)

原生sql查询:

@Test
	public void querySqlTest(){
		Session session=null;
		try{
			session=HibernateUtil.openSession();
			String sql="select * from t_student   where student_name like ?";
			SQLQuery query=session.createSQLQuery(sql);
			query.addEntity(Student.class);
			//从第几条记录开始
			query.setFirstResult(0);
			//每页大小
			query.setMaxResults(20);
			query.setString(0, "%王%");
			List<Student> list=query.list();
			for(Student stu: list){
				System.out.println(stu);
			}
		}finally{
			session.close();
		}
	}


对象导航查询(内连接):

@Test
	public void queryNavigationTest(){
		Session session=null;
		try{
			session=HibernateUtil.openSession();
			String hql="from Student stu where stu.user.userId=?";
			Query query=session.createQuery(hql);
			query.setInteger(0, 21);
			Student stu=(Student) query.uniqueResult();
			System.out.println(stu);
		}finally{
			session.close();
		}
	}


连接查询:

@Test
	public void queryJoinTest(){
		Session session=null;
		try{
			session=HibernateUtil.openSession();
			String hql="select stu from Student stu join stu.user u  where u.userId=?";
			Query query=session.createQuery(hql);
			query.setInteger(0, 21);
			Student stu=(Student) query.uniqueResult();
			System.out.println(stu);
		}finally{
			session.close();
		}
	}


左连接查询:

@Test
	public void queryLeftJoinTest(){
		Session session=null;
		try{
			session=HibernateUtil.openSession();
			String hql="select stu from Student stu left join stu.user u where u.userName is not null";
			Query query=session.createQuery(hql);
			List<Student> list=query.list();
			for(Student stu: list){
				System.out.println(stu);
			}
		}finally{
			session.close();
		}
	}



hibernate之13.hql(二)