为什么使用连接表的一对多双向映射使用内部和外部连接

时间:2014-09-12 03:12:33

标签: java sql hibernate

我正在关注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 JOINPersonAddress之间的单Address来获取数据。 INNER JOIN那么Hibernate首先使用LEFT OUTER JOIN然后使用{{1}}?有些人可以帮助我理解这一点。

0 个答案:

没有答案