Itable 대신 목록을 반환하는 CrudRepository에서 findAll()을 사용하는 방법
모든 학생 개체의 목록을 반환하는 FindAll() 메서드를 작성하고 싶습니다.그러나 CRUDR 저장소에는 Iterable<> findAll()만 있습니다.
목표는 모든 학생을 목록에 넣고 API 컨트롤러에 전달하여 모든 학생을 http GET로 가져올 수 있도록 하는 것입니다.
이 메서드를 목록으로 변환하는 가장 좋은 방법은 무엇입니까 <> 모두 찾기()
현재 코드에서 학생 서비스의 findAll 메서드는 다음과 같은 비호환 유형을 제공합니다.참을만 합니다.필수:목록 오류.
서비스
@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> {
}
추상적인 방법을 정의할 수 있습니다.List<Student> findAll()
에서StudentRepository
인터페이스다음과 같은 간단한 것이 있습니다.
public interface StudentRepository extends CrudRepository<Student, Long> {
List<Student> findAll();
}
JpaRepository에서 StudentRepository를 상속받도록 하면 다음과 같이 됩니다.findAll()
목록을 반환하는 메서드입니다.
public interface StudentRepository extends JpaRepository<Student, Long> {
}
참조:
CrudRepository의 경우 목록을 반환하려면 람다 식을 사용해야 합니다.
public List<Student> findAll() {
List<Student> students = new ArrayList<>();
studentRepository.findAll().forEach(students::add);
return students;
}
default List<Student> getStudentList() {
final List<Student> studentList = new LinkedList<>();
Iterable<Student> iterable = findAll();
iterable.forEach(studentList::add);
return studentList;
}
파티에 늦었지만, 제가 평소에 하는 방식은 이렇습니다.여기서는 CRUD 저장소가 다음과 같다고 가정합니다.DingDong
:
List<DingDong> dingdongs = StreamSupport //
.stream(repository.findAll().spliterator(), false) //
.collect(Collectors.toList());
두 가지 옵션:
기본 스프링 데이터 재정의
findAll()
목록을 반환하는 방법 - https://docs.spring.io/spring-data/data-commons/docs/1.6.1.RELEASE/reference/html/repositories.html#repositories.custom-implementations 참조
목록을 반환하는 서비스가 많이 있는 경우 몇 번을 수행해야 할 때 논리를 추출하도록 설정하는 두 번째 옵션을 추천합니다.
람다 표현식을 아직 사용하지 않았지만 여전히 작동하는 솔루션을 볼 수 있을 것으로 예상되는 사용자를 위한 오래된 접근법:
public List<Student> findAllStudents() {
Iterable<Student> findAllIterable = studentRepository.findAll();
return mapToList(findAllIterable);
}
private List<Student> mapToList(Iterable<Student> iterable) {
List<Student> listOfStudents = new ArrayList<>();
for (Student student : iterable) {
listOfStudents.add(student);
}
return listOfStudents;
}
더 간단한 방법이 있습니다.
List<Student> studentsList;
studentsList = (List<Student>) studentRepository.findAll();
추가할 위치CrudRepository
:
public interface StudentRepository extends CrudRepository<Student, Long> {
List<Student> findAll();
}
언급URL : https://stackoverflow.com/questions/56499565/how-to-use-findall-on-crudrepository-returning-a-list-instead-of-iterable
'source' 카테고리의 다른 글
윈도우즈 서버 2008 IIS 7에서 ASP.NET 4.5 MVC 4가 작동하지 않음 (0) | 2023.08.20 |
---|---|
버튼을 오른쪽으로 정렬합니다. (0) | 2023.08.20 |
수식을 편집하는 동안 (다른 시트의 셀을) 강조 표시하는 방법은 무엇입니까? (0) | 2023.08.20 |
스위프트에 있는 모든 물체와 모든 물체 (0) | 2023.08.20 |
IP 전화/IPad:화면 너비를 프로그래밍 방식으로 가져오는 방법은 무엇입니까? (0) | 2023.08.20 |