Java Spring : MongoRepository count() 和 findAll()
Java Spring : MongoRepository count() and findAll()
我注意到 mongo 的 Spring 数据有些奇怪:
MongoRepository
扩展了 CrudRepository
和 findAll()
returns 一个 Iterable
count()
方法没问题,因为它 returns一个long
.
class CrudRepository {
...
Iterable<T> findAll();
long count();
}
在 mongo MongoRepository
中 findAll()
方法返回一个 List
:
class MongoRepository extends CrudRepository {
...
@Override
List<T> findAll();
}
但是 List#size()
returns 和 int
以及 MongoRepository#count()
方法仍然返回一个 long。
当集合超过 Integer.MAX_VALUE
时会发生什么!?我们还能调用 List<T> findAll()
吗?
来自 java.util.List#size
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
方法将 return Integer.MAX_VALUE
。
Could we still call List<T> findAll()
?
是的,但是调用很可能会失败并显示 OutOfMemoryError
我喜欢你的观点 :) 根据你的要求,这个问题看起来很相似
如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 只是一个数组,我们不能存储超过 INTEGER.MAX_VALUE在一个数组列表中。 (当然,List 的不同实现可能会有不同的行为)
Spring Data JPA允许您自定义查询方式。您可以随时创建一个 returns 类型为 Iterable 的查询方法。
@Override
Iterable<T> findAll();
我注意到 mongo 的 Spring 数据有些奇怪:
MongoRepository
扩展了 CrudRepository
和 findAll()
returns 一个 Iterable
count()
方法没问题,因为它 returns一个long
.
class CrudRepository {
...
Iterable<T> findAll();
long count();
}
在 mongo MongoRepository
中 findAll()
方法返回一个 List
:
class MongoRepository extends CrudRepository {
...
@Override
List<T> findAll();
}
但是 List#size()
returns 和 int
以及 MongoRepository#count()
方法仍然返回一个 long。
当集合超过 Integer.MAX_VALUE
时会发生什么!?我们还能调用 List<T> findAll()
吗?
来自 java.util.List#size
javadoc:
Returns the number of elements in this list. If this list contains more than
Integer.MAX_VALUE
elements, returnsInteger.MAX_VALUE
.
因此,当集合大小超过 Integer.MAX_VALUE
时,size
方法将 return Integer.MAX_VALUE
。
Could we still call
List<T> findAll()
?
是的,但是调用很可能会失败并显示 OutOfMemoryError
我喜欢你的观点 :) 根据你的要求,这个问题看起来很相似
如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 只是一个数组,我们不能存储超过 INTEGER.MAX_VALUE在一个数组列表中。 (当然,List 的不同实现可能会有不同的行为)
Spring Data JPA允许您自定义查询方式。您可以随时创建一个 returns 类型为 Iterable 的查询方法。
@Override
Iterable<T> findAll();