How do I left join tables in unidirectional many-to-one in Hibernate?

jbarz picture jbarz · Mar 5, 2010 · Viewed 7.1k times · Source

I'm piggy-backing off of How to join tables in unidirectional many-to-one condition?.

If you have two classes:

class A {
    @Id
    public Long id;
}

class B {
    @Id
    public Long id;
    @ManyToOne
    @JoinColumn(name = "parent_id", referencedColumnName = "id")
    public A parent;
}

B -> A is a many to one relationship. I understand that I could add a Collection of Bs to A however I do not want that association.

So my actual question is, Is there an HQL or Criteria way of creating the SQL query:

select * from A left join B on (b.parent_id = a.id)

This will retrieve all A records with a Cartesian product of each B record that references A and will include A records that have no B referencing them.

If you use:

from A a, B b where b.a = a

then it is an inner join and you do not receive the A records that do not have a B referencing them.

I have not found a good way of doing this without two queries so anything less than that would be great.

Thanks.

Answer

Luciano picture Luciano · Mar 5, 2010

I've made an example with what you posted and I think this may work:

select a,b from B as b left outer join b.parent as a in HQL.

I have to find a "criteria" way of doing that though.