SpringBoot笔记之四:持久化数据之Mysql
小珏随笔 2017-06-10 20:04
在上一篇《SpringBoot笔记之三:用Thymeleaf渲染页面》中已经介绍了如何通过Thymeleaf模板渲染Web页面。这一篇文章来介绍下如何通过starter访问Mysql数据库、进行CRUD以及自定义的数据操作。
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,并插入测试数据。
student table initialization
DataSource配置
在application.properties配置文件中添加如下数据库配置。
mysql configuration
定义实体类
定义和数据库对应的Student实体类。
Student Entity
Repository类
Spring Data Repositories的目的是通过接口的形式简化DAO层的实现,提供了如下的默认接口。
除了支持如上的默认接口外,还支持如下形式的扩展。
这样,我们的StudentRepository类使用一个最简单的findById接口方法举例说明用法。
Student Repository
Controller层调用Repository
在Controller中注入StudentRepository即可对数据库进行操作。
Student Controller