我想编写一个 FindAll() 方法,它返回所有 Student 对象的列表。但是 CRUDRepository 只有 Iterable<> findAll()。
目标是让所有学生都进入一个列表并将其传递给 API 控制器,这样我就可以通过 http GET 获取所有学生。
将此方法转换为 List<> FindAll() 的最佳方法是什么
在我当前的代码中,StudentService 中的 findAll 方法为我提供了找到的不兼容类型:Iterable。必需:列表错误。
服务
@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控制器
@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());
}
}
学生资料库
public interface StudentRepository extends CrudRepository<Student, Long> {
}
原文由 Bram 发布,翻译遵循 CC BY-SA 4.0 许可协议
您可以简单地在
StudentRepository
接口中定义一个抽象方法List<Student> findAll()
。像这样简单的东西: