springboot中使用JOIN實現關聯表查詢

* 首先要確保你的表和想要關聯的表有外鍵鏈接java

  • repository中添加接口JpaSpecificationExecutor<?>,就可使用springboot jpa 提供的API了。
  • @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方法構建了查詢條件的集合
      •    這裏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其實蠻好用的,多用就知道了。編輯器

相關文章
相關標籤/搜索