Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between join and path navigation in jpa query

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?

like image 617
Deepika Kamboj Avatar asked Jan 04 '16 05:01

Deepika Kamboj


People also ask

What is path in JPA?

PathJPA interfaceRepresents a simple or compound attribute path from a bound type or collection, and is a "primitive" expression.

What is join in JPA?

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.

What is CriteriaBuilder in JPA?

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.

How do you join unrelated entities with JPA and Hibernate?

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.


2 Answers

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.

like image 187
Vlad Mihalcea Avatar answered Oct 26 '22 16:10

Vlad Mihalcea


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.

like image 44
Deepika Kamboj Avatar answered Oct 26 '22 17:10

Deepika Kamboj