Search code examples
jpaone-to-manymany-to-oneconstruct

Construct JPA query for a OneToMany relation


I've those 2 entities

Class A {
    @OneToMany(mappedBy="a")
    private List<B> bs;
}

Class B {

    @ManyToOne
    private A a;

    private String name;
}

1) I would like to construct a query that says get all A's that have at least one B with name ="mohamede1945"

2) I would like to construct a query that says get all A's that don't have any B with name = "mohamede1945"

Could anyone help me?


Solution

  • You can use the ANY and ALL constructs to filter the subquery. So something like

    1. FROM A aEntity WHERE 'mohamede1945' = ANY (SELECT bEntity.name FROM aEntity.bs bEntity)
    
    2. FROM A aEntity WHERE 'mohamede1945' <> ALL (SELECT bEntity.name FROM aEntity.bs bEntity)