当前位置: 首页 > 知识库问答 >
问题:

如何在CrudRepository上使用findAll()返回列表而不是Iterable[重复]

乐正乐湛
2023-03-14

我想写一个FindAll()方法,它返回所有学生对象的列表。但是CRUDRepository只有Iterable

目标是将所有学生放入一个列表中,并将其传递给API控制器,以便我可以使用http get获取所有学生。

将此方法转换为List的最佳方法是什么

在我当前的代码中,学生服务中的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> {

}

共有3个答案

乜安志
2023-03-14

如果让StudentRepository从JpaRepository继承,则通过返回列表,可以使用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--

田兴旺
2023-03-14

对于CrudRepository,需要使用lambda表达式才能返回列表

public List<Student> findAll() {
    List<Student> students = new ArrayList<>();
    studentRepository.findAll().forEach(students::add);
    return students;
}
储阳曦
2023-03-14

您可以简单地定义一个抽象方法列表

public interface StudentRepository extends CrudRepository<Student, Long> {
    List<Student> findAll();
}
 类似资料:
  • 我为此使用了一个服务类,但为了最小的可重复示例而删除了它。目前findAll()正在返回一个空数组,而它应该从h2返回一个带有员工实体json的数组。我仍然不清楚Spring如何将数据处理到h2数据库中,所以我想这可能是我的问题的根源。 控制器: 存储库: 实体: 数据sql: schema.sql:

  • 在Java 8中,我越来越多地用替换返回值。 所以我曾经有: 我现在使用: 我对此的论点是: 它强制执行基础列表的不变性。 它隐藏了存在基础列表的事实。之后可以将其更改为集合或其他结构,而无需更改方法签名 它很好地封装了该方法的用户希望对项进行处理,而不是对列表进行处理 如果需要,它可以在以后进行简单的并行化 事实上,现在,在我的代码中,返回<code>列表 显然,其中一些可以通过不可变集合来实现

  • 我试图访问MyModelClass上的getter方法,但我的代码返回

  • 我正在编写一个code-gen工具,用于使用Spring-Data-Jpa为Spring-boot应用程序生成后端连接代码,CrudRepository中的方法返回Iterable而不是List,这让我有点恼火,因为Iterable没有提供足够的功能,但是List提供了,所以我正在寻找将Iterable转换为List的最佳方法。 我看到了这篇关于将可迭代转换为集合的文章,我想知道,与其使用像Gua

  • 问题内容: 我正在尝试编写一个用于与last.fm API进行交互的小脚本。 我有一点使用的经验,但是以前使用它的方式似乎无效,而是返回一个空列表。 我删除了API密钥,因为我不知道它到底应该有多私密,并举了一个示例,说明了我在该位置接收的XML。 与API交互的类: 调用的get_now_playing方法: 我收到的xml样本: 问题答案: 问题在于, 如果给定标签名称,则仅搜索元素的直接后代