我们经过前面的学习,已经可以正式操作mysql数据库,进行增删改查了。我们前面已经讲过了通过mybatis操作mysql数据库,今天就来讲讲通过JPA来操作mysql数据库。学完本节,你会感慨springboot结合jpa操作数据库是如此的简单。好了,话不多说,我们开始在springboot中使用jpa。
一,创建springboot项目
1,创建一个新项目

2,定义项目名称,点击next

3,勾选Spring Web Starter

4,勾选jpa和mysql驱动

5,点击finish

到这里我们就成功的创建springboot项目,并在项目里引入jpa了。下面我们就来讲解下怎么使用jpa操作数据库。
二,配置数据库相关信息
我们需要在配置文件里配置数据相关的信息。

完整配置代码如下
# 数据库驱动
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
# 数据库用户名
spring.datasource.username=root
# 数据库密码
spring.datasource.password=123456
# 链接本地数据库
spring.datasource.url=jdbc:mysql://localhost:3306/sell?characterEncoding=utf-8&useSSL=false
# 每次启动项目时更新数据库
spring.jpa.hibernate.ddl-auto=update
我们这里用到了sell数据库,所以我们要先新建一个sell数据库。
创建sell数据库的sql语句
create database sell default character set utf8 collate utf8_general_ci;
三,编写一个实体类和数据库表一一对应
我们这里编写一个 Test类,这个test类会和我们的数据表test一一对应。然后表里有一个自增的id字段,和一个name字段。

@Repository
public interface TestDao extends JpaRepository<Test,Integer> {
}
四,实现一个持久层,用来操作数据库

五,实现一个controller用来供浏览器操作数据库
@RestController
public class TestController {
@Resource
TestDao dao;
@GetMapping("/add")
public Test add() {
Test test = new Test();
test.setName("编程小石头");
Test save = dao.save(test);
return save;
}
@GetMapping("/list")
public List<Test> list() {
List<Test> all = dao.findAll();
return all;
}
}
六,演示
1,增加一条数据

2,看下我们的数据表里,有成功添加这条数据

3,查询所有数据

到这里我们就成功的在springboot引入jpa,成功的实现的数据的增加和查询了,是不是很简单
源码下载
https://github.com/qiushi123/springboot-demos
视频讲解
https://edu.csdn.net/course/detail/23443
网友评论