【问题标题】:Spring Data JPA. How to get only a list of IDs from findAll() method弹簧数据 JPA。如何从 findAll() 方法中仅获取 ID 列表
【发布时间】:2015-07-31 15:27:00
【问题描述】:

我有一个非常复杂的模型。实体有很多关系等等。

我尝试使用 Spring Data JPA 并准备了一个存储库。

但是当我调用具有对象规范的方法 findAll() 时,由于对象非常大,因此会出现性能问题。我知道是因为当我调用这样的方法时:

@Query(value = "select id, name from Customer ")
List<Object[]> myFindCustomerIds();

我在性能方面没有任何问题。

但是当我调用时

List<Customer> findAll(); 

我在性能方面遇到了很大的问题。

问题是我需要使用客户规范调用 findAll 方法,这就是为什么我不能使用返回对象数组列表的方法。

如何编写一个方法来查找所有具有客户实体规范但仅返回 ID 的客户。

像这样:

List<Long> findAll(Specification<Customer> spec);
  • 在这种情况下我不能使用分页。

请帮忙。

【问题讨论】:

  • 这听起来正是 FetchType.LAZY 想要解决的问题。
  • 更好,但仍有 10 - 15 秒。从 find all with query 我得到 1-2 秒的结果。使用 Spring Data 可以解决这个问题。这意味着仅从特定列而不是所有对象获取值?
  • 我无法想象检索整行会比单列慢得多。你的数据库模式让我害怕!但我认为修复它可能是不可能的。希望其他人会回答。 Spring JPA 非常灵活,我认为您可以使用自定义@Query 轻松做到这一点。但我从来没有亲自做过
  • 看,这不是数据库的问题。你能想象在你的应用程序和数据库之间有一些代理吗?当您想要传输一个稀疏对象(例如具有两个字段)和当您想要传输一个具有许多关系的对象并且您不能使用延迟获取时,您是否看到了不同之处?这就是问题所在。

标签: spring spring-data-jpa specifications criteria-api


【解决方案1】:

为什么不使用@Query注解?

@Query("select p.id from #{#entityName} p")
List<Long> getAllIds();

我看到的唯一缺点是属性 id 发生更改时,但由于这是一个非常常见的名称并且不太可能更改(id = 主键),这应该没问题。

【讨论】:

  • 或者只是@Query("select id from #{#entityName}")
【解决方案2】:

Spring Data 现在使用 Projections 支持这一点:

interface SparseCustomer {  

  String getId(); 

  String getName();  
}

比在您的Customer 存储库中

List<SparseCustomer> findAll(Specification<Customer> spec);

编辑:
正如 Radouane ROUFID Projections with Specifications 所述,由于bug,目前无法正常工作。

但是您可以使用 specification-with-projection 库来解决这个 Spring Data Jpa 缺陷。

【讨论】:

  • 这真的适用于这个用例吗?似乎java无法区分这个和由存储库扩展的 JpaSpecificationExecutor 中的原始方法,我不知道该给该方法取哪个名称。
  • 投影不能使用规范。 JpaSpecificationExecutor 只返回一个由存储库管理的聚合根目录类型的列表 (List&lt;T&gt; findAll(Specification&lt;T&gt; var1);)
【解决方案3】:

我解决了这个问题。

(因此我们将有一个只有 id 和 name 的稀疏 Customer 对象)

定义自己的仓库:

public interface SparseCustomerRepository {
    List<Customer> findAllWithNameOnly(Specification<Customer> spec);
}

还有一个实现(记住后缀 - 默认为 Impl)

@Service
public class SparseCustomerRepositoryImpl implements SparseCustomerRepository {
    private final EntityManager entityManager;

    @Autowired
    public SparseCustomerRepositoryImpl(EntityManager entityManager) {
        this.entityManager = entityManager;
    }

    @Override
    public List<Customer> findAllWithNameOnly(Specification<Customer> spec) {
        CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
        CriteriaQuery<Tuple> tupleQuery = criteriaBuilder.createTupleQuery();
        Root<Customer> root = tupleQuery.from(Customer.class);
        tupleQuery.multiselect(getSelection(root, Customer_.id),
                getSelection(root, Customer_.name));
        if (spec != null) {
            tupleQuery.where(spec.toPredicate(root, tupleQuery, criteriaBuilder));
        }

        List<Tuple> CustomerNames = entityManager.createQuery(tupleQuery).getResultList();
        return createEntitiesFromTuples(CustomerNames);
    }

    private Selection<?> getSelection(Root<Customer> root,
            SingularAttribute<Customer, ?> attribute) {
        return root.get(attribute).alias(attribute.getName());
    }

    private List<Customer> createEntitiesFromTuples(List<Tuple> CustomerNames) {
        List<Customer> customers = new ArrayList<>();
        for (Tuple customer : CustomerNames) {
            Customer c = new Customer();
            c.setId(customer.get(Customer_.id.getName(), Long.class));
            c.setName(customer.get(Customer_.name.getName(), String.class));
            c.add(customer);
        }
        return customers;
    }
}

【讨论】:

    【解决方案4】:

    很遗憾,Projections 不适用于 specificationsJpaSpecificationExecutor 只返回一个由存储库管理的聚合根目录类型的列表 (List&lt;T&gt; findAll(Specification&lt;T&gt; var1);)

    实际的解决方法是使用元组。示例:

        @Override
        public <D> D findOne(Projections<DOMAIN> projections, Specification<DOMAIN> specification, SingleTupleMapper<D> tupleMapper) {
            Tuple tuple = this.getTupleQuery(projections, specification).getSingleResult();
            return tupleMapper.map(tuple);
        }
    
        @Override
        public <D extends Dto<ID>> List<D> findAll(Projections<DOMAIN> projections, Specification<DOMAIN> specification, TupleMapper<D> tupleMapper) {
            List<Tuple> tupleList = this.getTupleQuery(projections, specification).getResultList();
            return tupleMapper.map(tupleList);
        }
    
        private TypedQuery<Tuple> getTupleQuery(Projections<DOMAIN> projections, Specification<DOMAIN> specification) {
    
            CriteriaBuilder cb = entityManager.getCriteriaBuilder();
            CriteriaQuery<Tuple> query = cb.createTupleQuery();
    
            Root<DOMAIN> root = query.from((Class<DOMAIN>) domainClass);
    
            query.multiselect(projections.project(root));
            query.where(specification.toPredicate(root, query, cb));
    
            return entityManager.createQuery(query);
        }
    

    其中Projections 是根投影的功能接口。

    @FunctionalInterface
    public interface Projections<D> {
    
        List<Selection<?>> project(Root<D> root);
    
    }
    

    SingleTupleMapperTupleMapper 用于将TupleQuery 结果映射到要返回的Object。

    @FunctionalInterface
    public interface SingleTupleMapper<D> {
    
        D map(Tuple tuple);
    }
    
    @FunctionalInterface
    public interface TupleMapper<D> {
    
        List<D> map(List<Tuple> tuples);
    
    }
    

    使用示例:

            Projections<User> userProjections = (root) -> Arrays.asList(
                    root.get(User_.uid).alias(User_.uid.getName()),
                    root.get(User_.active).alias(User_.active.getName()),
                    root.get(User_.userProvider).alias(User_.userProvider.getName()),
                    root.join(User_.profile).get(Profile_.firstName).alias(Profile_.firstName.getName()),
                    root.join(User_.profile).get(Profile_.lastName).alias(Profile_.lastName.getName()),
                    root.join(User_.profile).get(Profile_.picture).alias(Profile_.picture.getName()),
                    root.join(User_.profile).get(Profile_.gender).alias(Profile_.gender.getName())
            );
    
            Specification<User> userSpecification = UserSpecifications.withUid(userUid);
    
            SingleTupleMapper<BasicUserDto> singleMapper = tuple -> {
    
                BasicUserDto basicUserDto = new BasicUserDto();
    
                basicUserDto.setUid(tuple.get(User_.uid.getName(), String.class));
                basicUserDto.setActive(tuple.get(User_.active.getName(), Boolean.class));
                basicUserDto.setUserProvider(tuple.get(User_.userProvider.getName(), UserProvider.class));
                basicUserDto.setFirstName(tuple.get(Profile_.firstName.getName(), String.class));
                basicUserDto.setLastName(tuple.get(Profile_.lastName.getName(), String.class));
                basicUserDto.setPicture(tuple.get(Profile_.picture.getName(), String.class));
                basicUserDto.setGender(tuple.get(Profile_.gender.getName(), Gender.class));
    
                return basicUserDto;
            };
    
            BasicUserDto basicUser = findOne(userProjections, userSpecification, singleMapper);
    

    我希望它有所帮助。

    【讨论】:

      【解决方案5】:

      您可以使用流来获取客户服务类中的所有 ID。

      public List<String> listIds() {
              return customerRepository.findAll().stream()
                      .map(customer -> customer.getId())
                      .collect(Collectors.toList());
          }
      

      【讨论】:

      • 您正在获取所有内容,这将导致性能问题
      • 完成了这项工作,但如果我们有 blob 数据,它会非常慢
      猜你喜欢
      • 2015-08-18
      • 2015-05-26
      • 2018-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多