springboot整合jpa的基本过程
1.整合基本步骤
添加依赖
在 pom.xml 文件中添加 Spring Boot 和 JPA 的依赖:
xml
<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>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
这里使用的是 H2 内存数据库,方便测试和演示。
创建实体类
创建 Person 实体类:
java
@Entity
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(nullable=false)
private String name;
@Column(nullable=false)
private Integer age;
// getter and setters
}
创建数据访问层
创建 PersonRepository 数据访问层:
java
@Repository
public interface PersonRepository extends JpaRepository<Person, Long> {
List<Person> findAllByOrderByAgeAsc();
}
这里继承了 JpaRepository 接口,JpaRepository 是一个 JPA 提供的基础接口,包含了常规的增删改查方法。我们只需要通过继承 JpaRepository 接口来继承这些方法,不需要自己手动写 SQL 语句。
创建控制器
创建 PersonController 控制器:
java
@RestController
@RequestMapping("/persons")
public class PersonController {
@Autowired
private PersonRepository personRepo;
@GetMapping
public List<Person> list() {
return personRepo.findAllByOrderByAgeAsc();
}
@PostMapping
public Person create(@Valid @RequestBody Person person) {
return personRepo.save(person);
}
}
这个类使用了 Spring MVC 的注解来定义 RESTful API。@GetMapping 和 @PostMapping 注解分别定义了 GET 和 POST 请求。@Valid 和 @RequestBody 注解用于验证请求参数和将请求参数转换成对象类型。
运行和测试
启动应用,在浏览器中访问 localhost:8080/persons,会返回一个空的 JSON 数组。使用 Postman 工具发送 POST 请求,按以下格式发送请求:
POST localhost:8080/persons
Content-Type: application/json
{
"name": "张三",
"age": 20
}
然后再次访问 localhost:8080/persons,就会返回一个包含刚刚添加的数据的 JSON 数组。
2.常用搭配配置项
spring:
datasource:
url: jdbc:mysql://localhost:3306/mydb
username: yourusername
password: yourpassword
driver-class-name: com.mysql.jdbc.Driver
jpa:
hibernate:
ddl-auto: update
show-sql: true
thymeleaf:
cache: false
mode: HTML
encoding: UTF-8
servlet:
content-type: text/html; charset=utf-8
security:
user:
name: yourname
password: yourpassword
其中:
- spring.datasource.: 数据源相关的配置项,包括 JDBC URL、用户名、密码和驱动器类名等。
spring.jpa.: JPA/Hibernate 相关的配置项,包括自动创建表的方式、显示 SQL 语句、方言等。
spring.thymeleaf.: Thymeleaf 模板引擎相关的配置项,包括缓存、模式和编码等。
spring.security.user.: Spring Security 相关的配置项,包括用户名和密码等。
基本内容就到这里了,更多内容查看本专栏。