* 首先要確保你的表和想要關聯的表有外鍵鏈接java
@Repository public interface MyEntityRepository extends JpaRepository<MyEntity, Integer>, JpaSpecificationExecutor<MyEntity> { //... }
在查詢方法中調用 JpaSpecificationExecutor 提供的 findAll() 方法,查詢到咱們須要的結果集,先上代碼,後續說明spring
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; }
代碼解釋:springboot
fKIds,這裏爲了順便記錄in查詢,我查詢的條件是 MyEntity.entityDetails.id in fKIds,就是關聯表字段的in查詢
sortField, pageNum爲分頁參數
toPredicate方法構建了查詢條件的集合
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其實蠻好用的,多用就知道了。編輯器