如何获取findAll()方法以在Iterable对象上工作

时间:2019-06-07 16:37:55

标签: java spring spring-boot spring-mvc

我正在尝试在服务层中编写一个返回对象列表的方法,以便可以将其传递给我的API控制器。我的findAll()方法给我错误:发现不兼容的类型:可迭代。必需:列表。因此,我认为使用Set而不是List可以给我:无法推断参数(无法解析构造函数)。

我不知道我在这里做错了什么,为什么我的学生对象被视为Iterable。任何帮助将不胜感激!

我的代码如下:

ServiceImpl

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

    //Cannot infer arguments (unable to resolve constructor)
    public Set<Student> getStudents()
    {
        Set<Student> students = new HashSet<>(studentRepository.findAll());
        return students;
    }

    public ArrayList<Student> getStudentsList(){
        return (ArrayList<Student>) this.studentRepository.findAll();
    }
}

服务

public interface StudentService {

    List<Student> findAll();
    Set<Student> getStudents();
    ArrayList<Student> getStudentsList()


}

API控制器

@RestController
@RequestMapping("/api/v1/students")

public class StudentAPIController {

    private final StudentRepository studentRepository;

    public StudentAPIController(StudentRepository studentRepository) {
        this.studentRepository = studentRepository;
    }

    //cannot resolve .getStudentsList
    @GetMapping
    public ResponseEntity<List<Student>> findAll() {
        return ResponseEntity.ok(StudentServiceImpl.getStudentsList);
    }

    @GetMapping
    public ResponseEntity<List<Student>> findAll() {
        return ResponseEntity.ok(StudentServiceImpl.findAll());
    }
}

普通StudentController

@Controller
@RequestMapping("/s")
public class StudentController {

    private final StudentRepository studentRepository;

    public StudentController(StudentRepository studentRepository){
        this.studentRepository = studentRepository;
    }

    @GetMapping
    public ModelAndView list(){
        Iterable<Student> students = this.studentRepository.findAll();
        return new ModelAndView("students/list" , "students", students);
    }

    @GetMapping("{id}")
    public ModelAndView view(@PathVariable("id") Student student) {
        return new ModelAndView("students/view", "student", student);
    }
}

StudentRepository

public interface StudentRepository extends CrudRepository<Student, Long> {

}

1 个答案:

答案 0 :(得分:0)

在JPA或Dao层中使用类似

public List<T> findAll() {
            return entityManager.createQuery("your query").getResultList();
    }