我來自Rails背景,正在深入研究Java。我一直在研究一個在MatchesController.java中定義了show操作的樣板項目;索引操作Java Spring Controller
@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中,show動作看起來像這樣;
def show
@match = Match.find(params[:id])
end
該索引動作看起來像;
def index
@matches = Match.all
end
我找我如何用Java編寫/春等效指標作用,我覺得我應該定義或使用某種類型的列表或數組對象,以檢索所有matchRepository的記錄:
我嘗試了類似下面的內容,但它當然是錯誤的,並且不會編譯。 show動作確實工作正常,並與我的本地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);
}
}
編譯錯誤;
[ERROR]編譯錯誤:
/Users/home/Latta/Spring/pong_matcher_spring/src/main/java/org/pongmatcher/web/MatchesController.java:[36,48]不兼容的類型:JAVA .util.List不能轉換到org.pongmatcher.domain.Match [INFO] 1個錯誤