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();
		}
	}



郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。