source

Itable 대신 목록을 반환하는 CrudRepository에서 findAll()을 사용하는 방법

lovecheck 2023. 8. 20. 11:55
반응형

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> {

}

참조:

https://docs.spring.io/spring-data/jpa/docs/current/api/org/springframework/data/jpa/repository/JpaRepository.html#findAll--

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());

두 가지 옵션:

  1. 서비스 메서드의 반복 가능한 목록을 인스턴스화하고 반복기를 배열 목록으로 변환합니다.

  2. 기본 스프링 데이터 재정의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

반응형