1

I am following the Hibernate documentation for Bidirectional one-to-many with Join tables between Person entity and Address entity and my mapping file is same as the one given in 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>

Now when I try to fetch the Person and the corresponding Address's using code:

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);
            }
        }

When the line person.getAddresses() is run then the query generated by hibernate is :

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=?

If we can get the data using only single LEFT OUTER JOIN between PersonAddress & Address then why Hibernate uses first and INNER JOIN then a LEFT OUTER JOIN? Can some please help me in understanding this.

learner
  • 6,062
  • 14
  • 79
  • 139
  • I would suggest, take a look at this [answer](http://stackoverflow.com/a/16827671/1679310). The point is that 8.5.1 mapping is really very very bad. Forget that. And because I would not recommend the many-to-many - try to think about the mapping with explicitly mapped pairing table. That will support better querying later... just suggestion ;) – Radim Köhler Sep 12 '14 at 04:59
  • @RadimKöhler, Thanks Radim, I will go through it. If possible can you please tell me answer for my query. – learner Sep 12 '14 at 17:33
  • What's the point of `optional="true"`? – Jimmy T. Sep 15 '14 at 19:13
  • @JimmyT., I am just following the docs and copied the same mapping given in docs, I am also not sure when we need to use that `optional` attribute. – learner Sep 16 '14 at 04:53

0 Answers0