I want to write a FindAll() method which returns a List of all Student objects. But the CRUDRepository only has Iterable<> findAll().
The goal is to get all students in a List and pass it to the API Controller so I can get all the students with a http GET.
What would be the best way to convert this method to List<> FindAll()
In my current code the findAll method in the StudentService gives me the Incompatible types found: Iterable. Required: List error.
Service
@Service
@RequiredArgsConstructor
public class StudentServiceImpl implements StudentService {
@Autowired
private final StudentRepository studentRepository;
//Incompatible types found: Iterable. Required: List
public List<Student> findAll() {
return studentRepository.findAll();
}
}
API Controller
@RestController
@RequestMapping("/api/v1/students")
public class StudentAPIController {
private final StudentRepository studentRepository;
public StudentAPIController(StudentRepository studentRepository) {
this.studentRepository = studentRepository;
}
@GetMapping
public ResponseEntity<List<Student>> findAll() {
return ResponseEntity.ok(StudentServiceImpl.findAll());
}
}
StudentRepository
public interface StudentRepository extends CrudRepository<Student, Long> {
}
For CrudRepository you will need to use lambda expression in order to return a list public List<Student> findAll () { List<Student> students = new ArrayList<> (); studentRepository.findAll ().forEach (students::add); return students; } If you make StudentRepository inherit from JpaRepository you have the findAll () method by returning a List.
The Spring Data CrudRepository has various methods that return multiple instances of the entity managed by the repository. It does so by using Iterable and not List, as one might expect. In many cases, that is of no consequence, since you typically want to iterate over the result anyway.
The Spring Data CrudRepository has various methods that return multiple instances of the entity managed by the repository. It does so by using Iterable and not List, as one might expect. In many cases, that is of no consequence, since you typically want to iterate over the result anyway. However, you might occasionally prefer a List.
You can simply define an abstract method List<Student> findAll () in the StudentRepository interface. Something simple like this: If you make StudentRepository inherit from JpaRepository you have the findAll () method by returning a List.
You can simply define an abstract method List<Student> findAll()
in the StudentRepository
interface. Something simple like this:
public interface StudentRepository extends CrudRepository<Student, Long> {
List<Student> findAll();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With