如何在返回 List 而不是 Iterable 的 CrudRepository 上使用 findAll()

新手上路,请多包涵

我想编写一个 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 许可协议

阅读 455
1 个回答

您可以简单地在 StudentRepository 接口中定义一个抽象方法 List<Student> findAll() 。像这样简单的东西:

 public interface StudentRepository extends CrudRepository<Student, Long> {
    List<Student> findAll();
}

原文由 Phong Bui 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题