有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

JavaSpring:MongoRepository count()和findAll()

我在mongo的Spring数据中发现了一些奇怪的东西:

MongoRepository扩展了CrudRepositoryfindAll()返回一个Iterable,当count()方法返回一个long时,它就可以了

class CrudRepository {

  ...

  Iterable<T> findAll();

  long count();
}

在mongo MongoRepositoryfindAll()方法返回List

class MongoRepository extends CrudRepository {

  ...  

  @Override
  List<T> findAll();
}

但是List#size()返回一个intMongoRepository#count()方法仍然返回一个long

当集合超过Integer.MAX_VALUE时会发生什么情况!?我们还能打电话给List<T> findAll()


共 (2) 个答案

  1. # 1 楼答案

    来自^{}javadoc:

    Returns the number of elements in this list. If this list contains more than Integer.MAX_VALUE elements, returns Integer.MAX_VALUE.

    因此,当集合大小超过Integer.MAX_VALUE时,size方法将返回Integer.MAX_VALUE

    Could we still call List<T> findAll()?

    是的,但是调用很可能会失败,因为OutOfMemoryError

  2. # 2 楼答案

    我喜欢你的观点:)根据你对this question.的要求,这个问题看起来很相似

    正如Java语言规范中提到的:15.10.1. Array Creation Expressions:

    Each dimension expression undergoes unary numeric promotion (§5.6.1). The promoted type must be int, or a compile-time error occurs.

    由于维度必须是整数,我们可以在数组中存储最大大小2,147,483,648,而且考虑到ArrayList只是一个数组,我们只能存储整数。数组列表中的最大值。(当然,列表的不同实现可能表现不同)

    Spring Data JPA允许您自定义查询方法。您始终可以自由创建一个查询方法,该方法返回的类型为Iterable

    @Override
    Iterable<T> findAll();