问题描述
只要你有一个扩展 CrudRepository 的存储库,例如:
@Repository
public interface EmployeeRepository extends CrudRepository<Employee,Long> {
//something
}
并且您想使用方法 findAll()
:
Iterable<T> findAll();
你会得到一个可迭代对象。显然,我可以将 Iterable 转换为列表,如下所示:
public List<Employee> findAll() {
List<Employee> employees = new ArrayList<>();
employeeRepository.findAll().forEach(employees::add);
return students;
}
或者我可以覆盖存储库上的 findAll()
方法,甚至我可以简单地使用 JpaRepository
,但我的问题是:
- 首先获得 Iterable 的目的是什么?将其转换为 List 是否违背了使用 CrudRepository 的全部目的?
- If 确实是将 Iterable 转换为 List 的好方法。实现这一目标的最有效方法是什么?
希望有人能给我一些见解。
解决方法
首先获得 Iterable 的目的是什么?
简而言之,返回 Iterable<T>
可能很有用,因为不仅 List<T>
是 Iterable<T>
,而且您可能想要返回不是的东西一个列表;
实现这一目标的最有效方法是什么?
我不确定您认为什么是最有效,但转换效果很好:
public List<Employee> findAll() {
return new ArrayList<>((Collection<? extends Employee>) employeeRepository.findAll());
}