zoukankan      html  css  js  c++  java
  • 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其实蛮好用的,多用就知道了。

  • 相关阅读:
    golang 数据结构 优先队列(堆)
    leetcode刷题笔记5210题 球会落何处
    leetcode刷题笔记5638题 吃苹果的最大数目
    leetcode刷题笔记5637题 判断字符串的两半是否相似
    剑指 Offer 28. 对称的二叉树
    剑指 Offer 27. 二叉树的镜像
    剑指 Offer 26. 树的子结构
    剑指 Offer 25. 合并两个排序的链表
    剑指 Offer 24. 反转链表
    剑指 Offer 22. 链表中倒数第k个节点
  • 原文地址:https://www.cnblogs.com/zhoujl-5071/p/10382976.html
Copyright © 2011-2022 走看看