0.启动MySql服务
1.引入pom坐标
pom.xml
<!-- jpa -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
2.配置数据库连接信息
application.yml
spring:
# 这里使用的mysql驱动版本为8.x,url需加上时区,驱动全类名需加上cj
datasource:
url: jdbc:mysql://localhost:3306/test?serverTimezone=Asia/Shanghai
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
jpa:
# 设置展示sql语句
show-sql: true
# 设置sql语句格式化
properties:
hibernate:
format_sql: true
3.编写实体类
Student.java
@Data // lombok
@Entity // 数据库映射表
public class Student {
@Id // 设置主键
@GeneratedValue(strategy = GenerationType.IDENTITY) // 主键生成策略
private Integer id;
private String name;
private Integer score;
private LocalDate birthday;
}
4.继承JpaRepository接口
StudentRepository.java
// extends JpaRepository<数据库映射实体类, 主键类型>
public interface StudentRepository extends JpaRepository<Student, Integer> {}
5.Controller测试
StudentHandler.java
@RestController
@RequestMapping("/jpa")
public class StudentHandler {
@Autowired
private StudentRepository studentRepository;
@GetMapping("/all")
public List<Student> findAll() {
List<Student> studentList = studentRepository.findAll();
return studentList;
}
@GetMapping("id/{id}")
public Student findById(@PathVariable("id") int id) {
Student student = studentRepository.findById(id).get();
return student;
}
}