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?
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With