我正在关注Person
实体和Address
实体之间Bidirectional one-to-many with Join tables的Hibernate文档,我的映射文件与doc中给出的相同:
<class name="Person">
<id name="id" column="personId">
<generator class="native"/>
</id>
<set name="addresses"
table="PersonAddress">
<key column="personId"/>
<many-to-many column="addressId"
unique="true"
class="Address"/>
</set>
</class>
<class name="Address">
<id name="id" column="addressId">
<generator class="native"/>
</id>
<join table="PersonAddress"
inverse="true"
optional="true">
<key column="addressId"/>
<many-to-one name="person"
column="personId"
not-null="true"/>
</join>
</class>
现在,当我尝试使用代码获取Person
和相应的Address's
时:
List<Person> persons = session.createQuery("from Person").list();
for (Person person : persons) {
System.out.println(person);
for (Address address : person.getAddresses()) {
System.out.println(address);
}
}
当运行person.getAddresses()
行时,hibernate生成的查询是:
Hibernate: select addresses0_.personId as personId2_1_0_, addresses0_.addressId as addressId1_2_0_, address1_.addressId as addressId1_0_1_, address1_1_.personId as personId2_2_1_
from PersonAddress addresses0_
inner join ADDRESS address1_ // INNER JOIN between PersonAddress & Address
on addresses0_.addressId=address1_.addressId
left outer join PersonAddress address1_1_ // Now LEFT OUTER JOIN with PersonAddress
on address1_.addressId=address1_1_.addressId
where addresses0_.personId=?
如果我们只能使用LEFT OUTER JOIN
和PersonAddress
之间的单Address
来获取数据。 INNER JOIN
那么Hibernate首先使用LEFT OUTER JOIN
然后使用{{1}}?有些人可以帮助我理解这一点。