Spring Boot 实战(9) springboot 整合 JPA,2021 必看
1. 引入 spring-boot-starter-data-jpa
pom.xml
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2. 编写数据源的相关配置
application.yml
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/springboot_jpa?serverTimezone=GMT%2B8
username: root
password: root
Jpa:
hibernate:
更新或创建数据表
ddl-auto: update
在控制台显示 sql
show-sql: true
注意: 第一次建表 create 后面用 update,要不然每次重启都会新建表
二、 整合 SpringData JPA
1. 编写一个实体类
实体类和数据表进行映射,并且配置好映射关系
User
// 使用 Jpa 注解配置映射关系
@Entity // 告诉 Jpa 这是一个实体类(和数据表映射的类
)
@Table(name = "tb_user") // 指定和那个数据表对应
public class User {
@Id // 标明这是一个主键
@GeneratedValue(strategy = GenerationType.IDENTITY) // 自增主键
private Integer id;
@Column(name = "last_name",length = 50) // 这是和数据表对应的一个列
private String lastName;
@Column // 默认列名就是属性名
private String email;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
2. 编写一个 Dao 接口来操作实体类对应的数据表
Dao 接口继承 JpaRepository 完成对数据库的操作
UserDao
public interface UserDao extends JpaRepository<User,Integer> {
}
3. 编写 Controller 层
@RestController
public class UserController {
评论