2

Whenever you have a repository extending CrudRepository such as:

@Repository
public interface EmployeeRepository extends CrudRepository<Employee, Long> {
    //something 
}

and you want to use the method findAll():

Iterable<T> findAll();

You will get an iterable. Obviously, I could convert the Iterable into a list, like this:

public List<Employee> findAll() {
    List<Employee> employees = new ArrayList<>();
    employeeRepository.findAll().forEach(employees::add);
    return students;
}

Or I could Override the findAll() method on the repository or even I could simply go with JpaRepository instead, but my questions are:

  1. What is the purpose of getting an Iterable in the first place? By converting it into a List am I going against the whole purpose of using CrudRepository?
  2. If indeed is a fine approach to convert the Iterable into a List. What is the most efficient way to achieve this?

Hope somebody can give me some insight on this.

Giorgi Tsiklauri
  • 9,715
  • 8
  • 45
  • 66
Reader
  • 101
  • 6

1 Answers1

2

What is the purpose of getting an Iterable in the first place?

Briefly speaking, returning Iterable<T> may be useful, as not only List<T>s are Iterable<T>s, and you might want to return something that is not a list;

What is the most efficient way to achieve this?

I'm not sure what you consider as most efficient, but casting would work just fine:

public List<Employee> findAll() {
    return new ArrayList<>((Collection<? extends Employee>) employeeRepository.findAll());
}
Giorgi Tsiklauri
  • 9,715
  • 8
  • 45
  • 66