简体   繁体   中英

How to join three tables using Spring JPA

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM