当前位置:首页 > 开发 > 编程语言 > Hibernate > 正文

Hibernate查询HQL实例

发表于: 2013-11-29   作者:alleni123   来源:转载   浏览:
摘要: 三个实体类对象: public class Team { private String id; private String name; private Set students=new HashSet(); } public class Course { private String id; private String name;
三个实体类对象:
public class Team
{
	private String id;
	
	private String name;
	
	private Set students=new HashSet();
}


public class Course
{
	private String id;
	
	private String name;
	
	private Set<Student> students;
}

public class Student  
{	
	
	private String id;
	
	private String cardId;
	
	private int age;
	
	private String name;
	
	private Set<Course> courses;

}



映射文件:


[b]Team.hbm.xml[/b]
<hibernate-mapping package="hql">
	<class name="Team" table="team">
	
 		<id name="id" column="id" type="string">
 			<generator class="uuid"></generator>
 		</id>
 		
	<property name="name" column="teamName" type="string"/>
	
	<set name="students" inverse="true" fetch="select" lazy="true">
		<key column="team_id"/>
		
		<one-to-many class="Student"/>
	</set>
 		
 		 
	</class>



</hibernate-mapping>



[b]Course.hbm.xml[/b]
<hibernate-mapping package="hql">
	<class name="Course" table="course">
	
 		<id name="id" column="id" type="string">
 			<generator class="uuid"></generator>
 		</id>
 		
	<property name="name" column="course_Name" type="string"/>
	
	<set name="students" inverse="true" fetch="select" lazy="true">
		<key column="course_id"/>
		
		<many-to-many class="Student" column="student_id"/>
	</set>
 		
 		 
	</class>



</hibernate-mapping>



[b]Student.hbm.xml[/b]
<hibernate-mapping package="hql">
	<class name="Student" table="student">
	
 		<id name="id" column="id" type="string">
 			<generator class="uuid"></generator>
 		</id>
 		
	<property name="name" column="student_Name" type="string"/>
	
	<set name="courses" inverse="true" fetch="select" lazy="true">
		<key column="student_id"/>
		
		<many-to-many class="Course" column="course_id"/>
	</set>
 	 <many-to-one name="team" fetch="select" column="team_id" class="Team"/>	
 		 
	</class>



</hibernate-mapping>





SQL插入语句:
create table course (
id varchar2(32) default '' not null  ,
course_name varchar2(45) default null,
primary key (id)
);

create table team(
id varchar2(32) default '' not null,
team_name varchar2(45),
primary key(id)
);

    

create table student(
id varchar2(32) default '' not null,
student_name varchar2(45) ,
student_age number(10)  ,
student_cardid varchar2(15)  ,
team_id varchar2(32) ,
primary key(id)
);

create table student_course(
student_id varchar2(32) not null,
course_id varchar2(32) not null
);


alter table student_course add constraint FK_dk062403lt7507oncwn9uo4ro foreign key  (course_id) references course;
alter table student_course add constraint FK_3shg469d7jsf2a81b5x62jlq1 foreign key  (student_id) references student;
alter table student add constraint FK_8eu2c4tg0i8amuwx6n6d4i8h0 foreign key (team_id) references team(id);


insert into  student values ('1','alleni',22,'111',null);
insert into  student values ('2','eline',23,'222',null);
insert into  student values ('3','doudou',8,'333',null);


insert into course values('111','Chinese');
insert into course values('222','Math');
insert into course values('333','English');
insert into course values('444','Physical');
insert into course values('555','Chemistry');
insert into course values('666','Geography');

insert into team values('team_a','drawer');
insert into team values('team_b','hunter');


update student set team_id ='team_a' where id='1';
update student set team_id ='team_a' where id='2';
update student set team_id ='team_b' where id='3';

insert into student_course values ('1','333');
insert into student_course values ('1','666');
insert into student_course values ('2','222');
insert into student_course values ('2','333');
insert into student_course values ('2','444');
insert into student_course values ('2','555');
insert into student_course values ('3','111');
insert into student_course values ('3','444');
insert into student_course values ('3','555');

 





=======================================================
HQL查询


方法1. 获取Object[]
/**
* Return the query results as a <tt>List</tt>. If the query contains
* multiple results pre row, the results are returned in an instance
* of <tt>Object[]</tt>.
*
* @return the result list
* @throws HibernateException
*/
public List list() throws HibernateException;


list方法可以返回一个Object[]类型对象,比如我们查询"select s.name,s.age from Student s",就会得到一个Object[]对象,如下所示:

  name     age
   xx       xx
   xx       xx

这里的每一行都是一个Object数组。因此我们可以通过强制类型转换,将其转换为Object[]。在这里其中[0]就是name,[1]就是age。   代码如下:

		Query query=session.createQuery("select s.name,s.age from Student s");
		
		List  list=query.list();
		
		for(int i=0;i<list.size();i++){
			Object[] obj=(Object[]) list.get(i);
			System.out.println(obj[0]+", "+obj[1]);
			//输出结果:alleni, 22
             //          eline, 23
             //          doudou, 8
		}



方法2.获取实例对象查询

		//这种方式将返回的离散的值作为一个Student类型对象传了回来。
		Query query=session.createQuery("select new Student(s.name,s.age) from Student s"); 
		
		List<Student> list=query.list();
		for(Student s:list){
                        System.out.println(s.getAge()); //有值
			System.out.println(s.getName()); //有值
                       System.out.println(s.getCardId()); //null
		}


这种方式适用于当我们只需要部分值的时候。
上面的例子就通过包含部分元素(name,age)的Student的构造函数来获取Student实例。
这里只查询了age和name。 而其它元素都是空的。

注意: 这里必须在Student类中声明一个构造函数:
  
	
 //这里的参数顺序必须和HQL语句中的new Student(s.name,s.age)一致。  
 public Student(String name,int age )
	{	
		
		this.age = age;
		this.name = name;
	}

没有这个构造函数,就会抛出异常(could not locate appropriate constructor)


方法3. 通过inner join进行查询
什么是内连接(inner join)?
select * from team join student on  team.id=student.team_id where team.id='team_a';
也就是查询出Student表中team id=team_a的。等价于:
select * from team,student where team.id=student.team_id ;  team.id='team_a';
(瞎写的,这里我也不会写)


具体代码实例:

		Session session=HibernateUtil.openSession();
		
		//Team中有students,这里用Team和Student进行一个内连接查询
		//这里就不再遵循映射配置的lazy,直接从两个表中获取查询的数据了。
		Query query=session.createQuery("from Team t  join t.students"); 
		
		List  list=query.list();
		
		System.out.println(list.size());
		
		session.close();
		
		for(int i=0;i<list.size();i++){
			//这里获取的数组,[0]是Team, [1]是Student
		 	Object[] obj=(Object[]) list.get(i);
			
		 	Team team=(Team) obj[0];
		 	Student student=(Student)obj[1];
			
		 	System.out.println(team.getName()+" : "+student.getName() );
		 	System.out.println(student.getCourses().iterator().next()); //course的内容并没有通过HQL语句中查询,所以这里会报错no Session
			
			//System.out.println(obj[0]+", "+obj[1]);
		}


输出结果为:
drawer : alleni
drawer : eline
hunter : doudou

可以看出Hibernate将inner join查询到的内容通过HQL语句格式,分别放入查询表所映射的类对象实例中。

方法4.通过实例对象进行查询

Session session=HibernateUtil.openSession();
		
		Team team=(Team)session.load(Team.class,"team_a");
		
		System.out.println(team.getName());
		
		
		Query query=session.createQuery("from Student s where s.team=:team and s.age >20" );
		query.setEntity("team", team); //通过setEntity高速Hibernate where s.team=:team这里team对应的实例。
		
		List list=query.list();
		System.out.println(list.size()); //2
		
		System.out.println(((Student)list.get(0)).getName());//alleni
		System.out.println(((Student)list.get(1)).getName()); //eline



方法5.通过条件过滤器进行查询

		Session session=HibernateUtil.openSession();
		
		Team team=(Team)session.load(Team.class,"team_a");
		
		System.out.println(team.getName());
		
		
	 
		
		Query query=session.createFilter(team.getStudents(), "where age>20");
		List list=query.list();
		System.out.println(list.size());
		
		System.out.println(((Student)list.get(0)).getName());
		System.out.println(((Student)list.get(1)).getName());

这里通过过滤器查询, 查询结果和方法4的一样。

Hibernate查询HQL实例

  • 0

    开心

    开心

  • 0

    板砖

    板砖

  • 0

    感动

    感动

  • 0

    有用

    有用

  • 0

    疑问

    疑问

  • 0

    难过

    难过

  • 0

    无聊

    无聊

  • 0

    震惊

    震惊

版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号