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

  • 相关阅读:
    【Vue前端】Vue前端注册业务实现!!!【代码】
    QQ第三方登录逻辑(微信,微博等同)
    发送短信验证码逻辑
    web图形验证码逻辑
    PID算法资料【视频+PDF介绍】
    如何配置电脑本地的域名
    js实现阻止默认事件preventDefault与returnValue
    js实现事件监听与阻止监听传播
    json字符串转换对象的方法1
    json字符串转换对象的方法
  • 原文地址:https://www.cnblogs.com/zhoujl-5071/p/10382976.html
Copyright © 2011-2022 走看看