一、pom.xml配置文件
<!-- 整合Spring Data jpa -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
二、Student
-
开头添加 @Entity
-
@Id 表示主键。
-
@GeneratedValue(strategy = GenerationType.IDENTITY) 表示自增
-
@Column 表示其他值
@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column
private String name;
@Column
private Integer age;
@Column
private LocalDate birthday;
}
三、StudentRepository
可以添加一部分符合命名规则的方法,jpa会自动实现。例如findById/getById
public interface StudentRepository extends JpaRepository<Student,Long> {
}
四、StudentHandler
@RestController
@RequestMapping("/student")
public class StudentHandler {
@Autowired
private StudentRepository studentRepository;
@GetMapping("/findAll")
public List<Student>findAll(){
return studentRepository.findAll();
}
@GetMapping("/findById/{id}")
public Student findById(@PathVariable("id") long id){
return studentRepository.findById(id).get();
}
@PostMapping("/save")
public void save(@RequestBody Student student){
studentRepository.save(student);
}
@PutMapping("/update")
public void update(@RequestBody Student student){
studentRepository.save(student);
}
@DeleteMapping("/deleteById/{id}")
public void delteById(@PathVariable("id") long id){
studentRepository.deleteById(id);
}
}
五、application.yml
spring:
datasource:
url: jdbc:mysql://localhost:3306/springBoot?serverTimezone=UTC
username: root
password: 147250
driver-class-name: com.mysql.cj.jdbc.Driver
jpa:
# 输出sql语句
show-sql: true
# 格式化sql语句
properties:
hibernate:
format_sql: true