Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 837
Skizzo Avatar asked Sep 03 '13 12:09

Skizzo


People also ask

How do you write a JPA query for many-to-many relationships?

In JPA we use the @ManyToMany annotation to model many-to-many relationships. This type of relationship can be unidirectional or bidirectional: In a unidirectional relationship only one entity in the relationship points the other. In a bidirectional relationship both entities point to each other.

What is many-to-many relationship JPA?

The Many-To-Many mapping represents a collection-valued association where any number of entities can be associated with a collection of other entities. In relational database any number of rows of one entity can be referred to any number of rows of another entity.

Is JPQL simpler than SQL?

JPQL syntax is very similar to the syntax of SQL. Having SQL like syntax is an advantage because SQL is a simple structured query language and many developers are using it in applications. SQL works directly against relational database tables, records and fields, whereas JPQL works with Java classes and instances.

How do you make a many-to-many relationship in Java?

Implementation in JPA. Modeling a many-to-many relationship with POJOs is easy. We should include a Collection in both classes, which contains the elements of the others. After that, we need to mark the class with @Entity and the primary key with @Id to make them proper JPA entities.


1 Answers

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

like image 75
James Avatar answered Oct 04 '22 13:10

James