Based on these two tables (and their corresponding entities) :
profiles(id, email, name)
items(id, profile_id, rank, price)
Profile(email, name)
Item(profile, rank, price)
I have to list all the profiles, ordered by the best rank of their items (it's a "top profile" list in fact).
Here is the SQL request like you can execute it in PHPMyAdmin for example:
SELECT AVG(i.rank) AS rank, p.* FROM profiles AS p LEFT OUTER JOIN items AS i ON p.id = i.profile_id GROUP BY p.id ORDER BY rank DESC;
I'm new to JPA and I can't find some examples about doing a LEFT OUTER JOIN with CriteriaBuilder (if it's the right thing to do).
I would really appreciate if someone would lead me to the right way (I'm not asking someone to do me the job, just having good clues).
Thank you very much! :)
The only way to join two unrelated entities with JPA 2.1 and Hibernate versions older than 5.1, is to create a cross join and reduce the cartesian product in the WHERE statement. This is harder to read and does not support outer joins. Hibernate 5.1 introduced explicit joins on unrelated entities.
A left outer join is a method of combining tables. The result includes unmatched rows from only the table that is specified before the LEFT OUTER JOIN clause. If you are joining two tables and want the result set to include unmatched rows from only one table, use a LEFT OUTER JOIN clause or a RIGHT OUTER JOIN clause.
There are three types of outer joins -- LEFT, RIGHT and FULL. A LEFT JOIN contains all the records of the "left" table specified in the join command -- i.e., the one that's listed first -- plus any matching records in the "right" table.
This query can be expressed in JPQL as follows:
SELECT p, AVG(i.rank) as rank
FROM Item i RIGHT JOIN i.profile p
GROUP BY p
ORDER BY rank DESC
Note that you can't write arbitrary JOIN
s in JPA, only JOIN
s over relationships, therefore you need a RIGHT JOIN
here, because your relationship is unidirectional and source of the relationship should be at the left side.
This query could be translated in JPA 2.0 Criteria API in pretty straightforward way, however, the last time I checked it Hibernate's implementation of Criteria API didn't support right joins (and Play Framework uses Hibernate underneath). So, I think you have to use JPQL query in this case.
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