使用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的一個屬性。