span
span

Reputation: 5624

JPQL to select entity based on grandchild attribute

I am trying to select an entity A that has a B that contains a list of C where the value C.d must match a parameter.

My entities look like this:

@Entity
class A {

    @GeneratedValue
    @Id
    private Long id;

    @Column(name="B")
    @OneToOne(cascade=CascadeType.ALL)
    @MapsId
    private B b1;
}

@Entity
class B {

    @GeneratedValue
    @Id
    private Long id;

    @OneToMany(mappedBy="b2", cascade=CascadeType.ALL)
    private List<C> cs;
}

@Entity
class C {

    @GeneratedValue
    @Id
    private Long id;

    @ManyToOne
    @JoinColumn(name="B")
    private B b2;

    private String d;
}

My naive approach on selecting my entity look like this:

SELECT entity FROM A entity WHERE entity.b1.cs.d = :d

How should the query be structured?

Upvotes: 0

Views: 114

Answers (2)

Amer Qarabsa
Amer Qarabsa

Reputation: 6574

try this

    TypedQuery<A> query = em.createQuery("select b.a from B b inner join C c where c.d = :d",A.class);
List<A> a = query.getResultList();

Upvotes: 0

Daniel Hern&#225;ndez
Daniel Hern&#225;ndez

Reputation: 4266

Should be:

SELECT entity FROM A entity INNER JOIN entity.b1.cs CSList WHERE CSList.d = :d

Read about INNER JOIN in JPA.

http://www.thejavageek.com/2014/03/24/jpa-inner-joins/

Upvotes: 1

Related Questions