Bra*_*ram 3 java spring spring-mvc spring-boot
我想编写一个 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();
}
}
Run Code Online (Sandbox Code Playgroud)
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());
}
}
Run Code Online (Sandbox Code Playgroud)
学生资料库
public interface StudentRepository extends CrudRepository<Student, Long> {
}
Run Code Online (Sandbox Code Playgroud)
Pho*_*Bui 10
您可以简单地List<Student> findAll()在StudentRepository接口中定义一个抽象方法。像这样简单的事情:
public interface StudentRepository extends CrudRepository<Student, Long> {
List<Student> findAll();
}
Run Code Online (Sandbox Code Playgroud)
对于 CrudRepository,您需要使用 lambda 表达式才能返回列表
public List<Student> findAll() {
List<Student> students = new ArrayList<>();
studentRepository.findAll().forEach(students::add);
return students;
}
Run Code Online (Sandbox Code Playgroud)
如果您让 StudentRepository 从 JpaRepository 继承,您就可以findAll()通过返回一个列表来获得该方法。
public interface StudentRepository extends JpaRepository<Student, Long> {
}
Run Code Online (Sandbox Code Playgroud)
参考资料:
两种选择:
在服务方法中实例化可迭代对象的列表,然后像将迭代器转换为 ArrayList中那样返回该列表
覆盖默认的 spring datafindAll()方法以返回列表 - 请参阅https://docs.spring.io/spring-data/data-commons/docs/1.6.1.RELEASE/reference/html/repositories.html#repositories.custom-实施
如果有许多服务将返回列表,我建议您使用第二个选项来设置您在必须执行几次操作时提取逻辑。
| 归档时间: |
|
| 查看次数: |
28955 次 |
| 最近记录: |