注意:编写 Spring Data JPA 的 Repository 不需要使用 @Repository 注解!
使用 Repository:
package cn.com.iamddch.sia1;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/student")
public class StudentController {
// 注入 Repository
private final StudentRepository studentRepository;
@Autowired
public StudentController(StudentRepository studentRepository) {
this.studentRepository = studentRepository;
}
@GetMapping("/all")
public List<Student> getAllStudent() {
return studentRepository.findAll();
}
@PostMapping("/add")
public void addStudent(@RequestBody Student student) {
if (student.getId() != null) {
// client should not specify id
student.setId(null);
}
studentRepository.save(student);
}
}
使用 Spring Data JPA 简单且优雅,你不需要自己编写 .sql 文件来建表,因为 Spring Data JPA 会依照实体类自动生成;你也不需要自己编写 SQL 查询语句,因为 Spring Data JPA 已经预定义了很多基础操作,而自己添加一些查询也可以不需要编写 SQL 语句(之后你将看到)。不是每一个后端开发者都是 DBA (Database Administrator),而 Spring Data JPA 就是你最好的选择。