Skizzo
Skizzo

Reputation: 2983

Many-to-Many query jpql

I have the followed trouble.

There is an entity Distributor who is connected with the ManyToMany relationship to entity town:

@Entity
public class Distributor{

   @ManyToMany
   @JoinTable( name = "GS_DISTRIBUTOR_TOWN",
           joinColumns = @JoinColumn(name = "CD_DISTRIBUTOR"),
           inverseJoinColumns = @JoinColumn(name = "CD_TOWN") )
   private List<Town> towns;

   ....
}

Then the entity town is also in relation with District

@Entity
public class Town{

   @ManyToMany(mappedBy="towns")
   private List<Distributor> distributors;

   @ManyToOne
   private District district;

   ....
}

Now i have to filter(with jpql) all distributor who are in a district. How can i do?

Upvotes: 36

Views: 53124

Answers (2)

kathare kelvin
kathare kelvin

Reputation: 17

First, from the entity Town, there is incorrect relationship mapping for @Manytoone. Should be:

@Entity
public class District {

  .....

   @ManyToOne
   private Town town;

   ....
}

Upvotes: -3

James
James

Reputation: 18379

select distinct distributor 
from Distributor distributor  
join distributor.towns town 
join town.district district 
where district.name = :name

See: https://en.wikibooks.org/wiki/Java_Persistence/JPQL

Upvotes: 85

Related Questions