java - 索引操作 Java Spring Controller

标签 java ruby-on-rails spring-mvc ruby-on-rails-4 controller

我有 Rails 背景,正在深入研究 Java。我一直在开发一个样板项目,该项目在 MatchesController.java 中定义了一个显示操作;

@RestController
final class MatchesController {

private final MatchRepository matchRepository;

@Autowired
MatchesController(MatchRepository matchRepository) {
    this.matchRepository = matchRepository;
}

@RequestMapping(method = RequestMethod.GET, value = "/matches/{id}")
ResponseEntity<Match> show(@PathVariable String id) {
    Match match = matchRepository.findOne(id);

    if (match == null) {
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    } else {
        return new ResponseEntity<>(match, HttpStatus.OK);
    }
  }
}

在 Rails 中,显示操作看起来像这样;

def show
  @match = Match.find(params[:id])
end

索引操作看起来像;

def index
  @matches = Match.all
end

我正在寻找如何在 Java/Spring 中编写等效的索引操作,我觉得我应该定义或使用某种列表或数组对象来检索所有 matchRepository 记录:

我尝试了类似以下的操作,但当然它是错误的并且无法编译。显示操作确实工作正常并且与我的本地 mysql 数据库交互得很好。我只是一个完整的 java/spring 新手,正在闲逛。

@RequestMapping(method = RequestMethod.GET, value = "/matches")
ResponseEntity<Match> index() {
    Match matches = matchRepository.findAll();

    if (matches == null) {
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    } else {
        return new ResponseEntity<>(matches, HttpStatus.OK);
    }
}

编译错误;

[错误]编译错误:

/Users/home/Latta/Spring/pong_matcher_spring/src/main/java/org/pongmatcher/web/MatchesController.java:[36,48] 不兼容的类型:java.util.List 无法转换为 org.pongmatcher .domain.Match [信息] 1 个错误

最佳答案

看来你的MatchRepository#findAll()方法的返回类型为 List<Match> 。您不能将这样的值分配给 Match 类型的变量。

你需要

List<Match> matches = matchRepository.findAll();

然后需要更改您的返回类型以匹配

ResponseEntity<List<Match>> index() {

Java 是强类型的。

此外,如果尚未包含,则必须导入 List 包。

import java.util.List;

关于java - 索引操作 Java Spring Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27337759/

相关文章:

java - 如何获取先科的ZoneId?

java - 在 JSP 页面中运行 .jar 文件

java - 使用正则表达式在字符串中查找子字符串

ruby-on-rails - "use"Ruby/Rails/Rack 代码中的关键字/词

java - Spring 测试 - 注入(inject)具有嵌套 bean 依赖项的模拟 bean

java - 无法迭代 Jsp 中的列表

连接 php apache 时的 Java 杂项行为

ruby-on-rails - Ruby XMLRPC 本地主机运行时错误 : Wrong Size

ruby-on-rails - 在 Rails 中使用 Mocha 测试 form_for 路径生成

jquery - Spring MVC,Ajax post JSON对象,不允许405方法