springboot中使用JOIN实现关联表查询

* 首先要确保你的表和想要关联的表有外键连接

  • 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其实蛮好用的,多用就知道了。

猜你喜欢

转载自www.cnblogs.com/zhoujl-5071/p/10382976.html