使用HQL的Join进行关联查询,需要具备以下几个条件:
以Person和Car为例(Person与Car是一对多的关系)
1. 一对多的关系需要体现到实体类和配置文件中(注解也一样)
2. from关键字后面只有一个实体类名,也就是Person。Join使用的时候,实际上是join的Person的属性
下面写一个完整的例子:
1、数据结构:
create table one11_person(
id varchar(32) not null,
name varchar(20)
);
alter table one11_person
add constraint one11_person_pk primary key(id);
create table one11_car(
id varchar(32) not null,
name varchar(20),
personid varchar(32)
);
alter table one11_car
add constraint one11_car_pk primary key(id);
alter table one11_car
add constraint one11_car_fk foreign key(personid) references one11_person(id);
2:hbm.xml文件:
Person.hbm.xml文件:
<hibernate-mapping>
<class name="com.one11.One11Person" table="one11_person" catalog="spring">
<id name="id" type="java.lang.String">
<column name="id" length="32" />
<generator class="uuid" />
</id>
<property name="name" type="java.lang.String">
<column name="name" length="20" />
</property>
<set name="one11Cars" cascade="all">
<key>
<column name="personid" length="32" />
</key>
<one-to-many class="com.one11.One11Car" />
</set>
</class>
</hibernate-mapping>
Car.bbm.xml文件:
<hibernate-mapping>
<class name="com.one11.One11Car" table="one11_car" catalog="spring">
<id name="id" type="java.lang.String">
<column name="id" length="32" />
<generator class="uuid" />
</id>
<many-to-one name="one11Person" class="com.one11.One11Person" fetch="select">
<column name="personid" length="32" />
</many-to-one>
<property name="name" type="java.lang.String">
<column name="name" length="20" />
</property>
</class>
</hibernate-mapping>
3:类文件略。
4:关联查询代码:
public void query(){
Session s = HibernateUtil.getSessionFactory().getCurrentSession();
s.beginTransaction();
List list = s.createQuery("select new map(p.name as pname,c.name as cname) from One11Person as p join p.one11Cars as c").list();
s.getTransaction().commit();
System.err.println(list);
}
粗体部分为查询语句。其中使用了new map()和join关键字。对于join之后的one11Cars属于p的一个属性。