Hibernate join two classes via a common class field

Let's say I have Hibernate entity class A, B, C. B is a field of both A and C. Now, I want to retrieve A based on a condition of C's other fields. How can I do that?

@Entity
@Table(name = "A")
@Proxy(lazy = false)
public class A {
    ...

    @ManyToOne
    @JoinColumn(name = "b_ID")
    private B b;    

    ...
}

@Entity
@Table(name = "C")
@Proxy(lazy = false)
public class C {
    ...

    @ManyToOne(targetEntity=B)
    @JoinColumn(name="b_ID")
    private B b;   

    ...
}

@Entity
@Table(name = "B")
@Proxy(lazy = false)
public class B {
    ...
}

Now I want to get a list of A, that when C's records satisfy some condition. Thanks in advance.

You can do something like:

SELECT a FROM A a JOIN a.b b WHERE b.c.att = :value

There's even more alternatives.
I tried to show you that you can use JOINs or use the full path for any attribute. For example:

SELECT a FROM A a WHERE a.b.c.att = :value
SELECT a FROM A a JOIN a.b b JOIN b.c c WHERE c.att = :value

You can write a criteria query to achieve this :

Criteria criteria = session.createCriteria(A.class)

0 Comment

NO COMMENTS

LEAVE A REPLY

Captcha image