I have the following 2 entities:
class User {
private String name;
private UserType userType;
}
class UserType {
private String name;
}
I want to fetch all Users with userType name equal to 'admin'. I can write the following 2 queries that return the same result.
select u from User u where u.userType.name = 'admin';
and
select u from User u join u.userType ut where ut.name = 'admin';
Just wanted to understand which approach is preferable and what is the difference. If I can always get the result using navigation between entities when will I want to follow the join approach?
PathJPA interfaceRepresents a simple or compound attribute path from a bound type or collection, and is a "primitive" expression.
First of all, JPA only creates an implicit inner join when we specify a path expression. For example, when we want to select only the Employees that have a Department, and we don't use a path expression like e. department, we should use the JOIN keyword in our query.
The CriteriaBuilder can be used to restrict query results based on specific conditions, by using CriteriaQuery where() method and providing Expressions created by CriteriaBuilder. Let's see some examples of commonly used Expressions.
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.
Technically, they are equivalent but the second one is much more flexible.
With the explicit join syntax, you can change the JOIN
to LEFT JOIN
with an ON
criteria:
select u
from User u
left join u.userType ut on ut.name = 'admin'
This query will always return a User even if it doesn't have a user type, so sometimes that's desirable for some particular use cases.
On analysing the SQL generated by the two queries (jpa + Spring Data) it was observed that navigation leads to a cross join whereas mentioning only 'join' leads to an inner join by default.
Hence Navigation is not as efficient as explicitly joining on the required columns.
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