Reputation: 531
I need some help with Spring JPA.
I have an ID that comes in on a request, and I need to retrieve 2 fields - itemsOrdered, itemsDelivered from 2 tables.
The relationship between these tables is not straightforward, as given below.
Table A has ID (from request) as PK. Table A has a foreign key relationship with Table B. Table B has a foreign key relationship with Table C, Table D.
Right now to read itemsOrdered, itemsDelivered, I do it one by one.
A a = CrudRepository.findOne(id from request);
B b = CrudRepository.findOne(A.getID());
C c = CrudRepository.findOne(B.getID());
D d = CrudRepository.findOne(B.getID());
Is there anyway to do a join so that I can get C.itemsOrdered and d.itemsDelivered in one step?
Upvotes: 0
Views: 3172
Reputation: 30309
If you are using Hibernate 5.1+ (or simply Spring Boot 2.0+) you can use "join with conditions" in JPQL queries as in regular SQL, for example:
select
c.itemsOrdered,
d.itemsDelivered
from
A a
join B b on b.a_id = a.id
join C c on c.b_id = b.id
join D d on d.b_id = b.id
where
a.id = ?1
And with help of projections you can easily retrieve those fields:
public interface TwoFieldsProjection {
Long getItemsOrdered();
Long getItemsDelivered();
}
@Query("select c.itemsOrdered as itemsOrdered, d.itemsDelivered as itemsDelivered from A a join B b on b.a_id = a.id join C c on c.b_id = b.id join D d on d.b_id = b.id where a.id = ?1")
Optional<TwoFieldsProjection> getTwoFields(Long aId);
Note to use aliases in your query (c.itemsOrdered as itemsOrdered
) which names must match with getters in the projection.
Upvotes: 1