I am fairly new to Spring Data and I want to create a query that will allow me to do an Inner Join between two entities.
I have been using this stack overflow to try to clarify certain aspects:
How To Define a JPA Repository Query with a Join
It gives the answer of structuring the query as so:
@Query("select u.userName from User u inner join u.area ar where ar.idArea = :idArea")
However in this query I dont see where it manages to define "ar" as neither of the entity classes actually define "ar" within themselves? Any clarification on this would be greatly appreciated!
Consider this example
SELECT c FROM Country c
Here, c is called a range variable.
Range variables are query identification variables that iterate over all the database objects of a specific entity class hierarchy (i.e. an entity class and all its descendant entity classes)
You can read more about range variables here
As per your query that there is no "Area ar" you need to understand that this query is based on JPQL (not SQL). Consider the below query:
SELECT c1, c2 FROM Country c1 INNER JOIN c1.neighbors c2
JPQL provides something called as a join variable, which represent a more limited iteration over specified collections of objects. In the above query, c1 is a range variable while c2 is a join variable that is bound to the path c1.neighbours and iterates only over objects in that collection.
You can read about it in more detail in this article
area is actually defined in User entity class and in your query area is aliased with "ar" and used as second entity of the join.
@Query("select u.userName from User u inner join **u.area** ar
where ar.idArea = :idArea")
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