SpringBoot笔记之四:持久化数据之Mysql

在上一篇《SpringBoot笔记之三:用Thymeleaf渲染页面》中已经介绍了如何通过Thymeleaf模板渲染Web页面。这一篇文章来介绍下如何通过starter访问Mysql数据库、进行CRUD以及自定义的数据操作。

SpringBoot笔记之四:持久化数据之Mysql

MySql Logo

添加Maven依赖

为了访问mysql数据,需要引入如下依赖

  • spring-boot-starter-data-jpa: JPA(Java Persistence API)是Sun官方提出的Java持久化规范。它为Java开发人员提供了一种对象/关联映射工具来管理Java应用中的关系数据。

  • mysql-connector-java: 访问Mysql数据库的驱动。

初始化Mysql测试数据

在springboot用户名下使用如下sql进行建表springboot_test.student,并插入测试数据。

SpringBoot笔记之四:持久化数据之Mysql

student table initialization

DataSource配置

在application.properties配置文件中添加如下数据库配置。

SpringBoot笔记之四:持久化数据之Mysql

mysql configuration

定义实体类

定义和数据库对应的Student实体类。

SpringBoot笔记之四:持久化数据之Mysql

Student Entity

Repository类

Spring Data Repositories的目的是通过接口的形式简化DAO层的实现,提供了如下的默认接口。

SpringBoot笔记之四:持久化数据之Mysql

SpringBoot笔记之四:持久化数据之Mysql

SpringBoot笔记之四:持久化数据之Mysql

除了支持如上的默认接口外,还支持如下形式的扩展。

SpringBoot笔记之四:持久化数据之Mysql

SpringBoot笔记之四:持久化数据之Mysql

这样,我们的StudentRepository类使用一个最简单的findById接口方法举例说明用法。

SpringBoot笔记之四:持久化数据之Mysql

Student Repository

Controller层调用Repository

在Controller中注入StudentRepository即可对数据库进行操作。

SpringBoot笔记之四:持久化数据之Mysql

Student Controller

访问Controller

SpringBoot笔记之四:持久化数据之Mysql

小结

SprintBoot的配置极大的简化了对数据库操作的配置,jpa starter同样提供了封装好的接口对数据库进行访问,对数据库的访问变得非常容易。