* 首先要確保你的表和想要關聯的表有外鍵連接
- repository中添加接口JpaSpecificationExecutor<?>,就可以使用springboot jpa 提供的API了。
-
@Repository public interface MyEntityRepository extends JpaRepository<MyEntity, Integer>, JpaSpecificationExecutor<MyEntity> { //... }
在查詢方法中調用 JpaSpecificationExecutor 提供的 findAll() 方法,查詢到我們需要的結果集,先上代碼,后續說明
-
-
public Page<MyEntity> getMerchants(List<Integer> fKIds, String sortField, String entityName, Integer pageNum) { Pageable pageable = PageRequest.of(pageNum, 20, Direction.DESC, sortField); @SuppressWarnings("serial") Page<MyEntity> page = myEntityRepository.findAll(new Specification<MyEntity>() { @Override public Predicate toPredicate(Root<MyEntity> root, CriteriaQuery<?> query, CriteriaBuilder cb) { if (fKIds!= null) { Join<MyEntity, EntityDetails> join = root.join("entityDetails"); list.add(join .get("id").in(fKIds)); } Predicate[] array = new Predicate[list.size()]; return cb.and(list.toArray(array)); } }, pageable); return page; }
代碼解釋:
-
fKIds,這里為了順便記錄in查詢,我查詢的條件是 MyEntity.entityDetails.id in fKIds,就是關聯表字段的in查詢
-
sortField, pageNum為分頁參數
-
toPredicate方法構建了查詢條件的集合
- 這里join的精髓就是,獲取join對象,通過join對象進行查詢條件的構建。
-
javax.persistence.criteria.Join<MyEntity, EntityDetails> A join to an entity, embeddable, or basic type. Type Parameters:<Z> the source type of the join
<X> the target type of the join
Since:Java Persistence 2.0
-
-
低調總結:真的不太用的來博客園這個編輯器(^_^),JPA其實蠻好用的,多用就知道了。