Learner
Learner

Reputation: 21393

Why LEFT OUTER Join is needed for one-to-one bidirectional association

I am following Hibernate documentation for bidirectional one-to-one relationship and created one-to-one mapping between Person and Address entities.

The mapping is like the one given in document:

<class name="Person">
    <id name="id" column="personId">
        <generator class="native"/>
    </id>
    <many-to-one name="address" 
        column="addressId" 
        unique="true"
        not-null="true"/>
</class>

<class name="Address">
    <id name="id" column="addressId">
        <generator class="native"/>
    </id>
   <one-to-one name="person" 
        property-ref="address"/>
</class>

Now I created s smll program to fetch the Person and the corresponding Address like this:

    List<Person> persons = session.createQuery("from Person where id=2").list();
    for (Person person : persons) {
        System.out.println(person);
        System.out.println(person.getAddress());
        System.out.println(person.getAddress().getPerson());
    }

For the line person.getAddress(), hibernate issues a LEFT OUTER JOIN query as:

select
        address0_.addressId as addressId1_0_0_,
        person1_.personId as personId1_1_1_,
        person1_.addressId as addressId3_1_1_ 
    from
        ADDRESS address0_ 
    left outer join
        PERSON person1_ 
            on address0_.addressId=person1_.addressId 
    where
        address0_.addressId=?

If a inner join is sufficient in this case then why hibernate uses left outer join? Please clarify.

Upvotes: 3

Views: 2267

Answers (1)

alexander zak
alexander zak

Reputation: 939

Hibernate is loading the address using it's id (which it got from the PERSON). During the loading it is not sure whether the address has a person (it does not remember where it got the id from).

If the address had no person, and it used an inner join, no results would be returned. It uses outer join, so that if there is no person, a result will be returned with NULL in columns of the person.

This is what hibernate wants, so it uses outer join.

Upvotes: 5

Related Questions