spring data jpa 官网的介绍
Spring Data JPA, part of the larger Spring Data family, makes it easy to easily implement JPA based repositories. This module deals with enhanced support for JPA based data access layers. It makes it easier to build Spring-powered applications that use data access technologies.
Implementing a data access layer of an application has been cumbersome for quite a while. Too much boilerplate code has to be written to execute simple queries as well as perform pagination, and auditing. Spring Data JPA aims to significantly improve the implementation of data access layers by reducing the effort to the amount that’s actually needed. As a developer you write your repository interfaces, including custom finder methods, and Spring will provide the implementation automatically.
spring data jpa 是什么
它是Spring基于ORM框架、JPA规范封装的一套JPA应用框架,可使开发者用极简的代码即可实现对数据的访问和操作。它提供了包括增删改查等在内的常用功能,且易于扩展。学习并使用Spring Data JPA可以极大提高开发效率。
新建项目,增加依赖
在 Intellij IDEA 里面新建一个 SpringBoot 项目后,添加如下依赖
org.springframework.boot
spring-boot-starter-data-jpa
mysql
mysql-connector-java
5.1.6
项目配置
在配置文件application.properties中增加如下配置
#通用数据源配置spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driverspring.datasource.url=jdbc:mysql://{ip}:3306/{db}?charset=utf8mb4&useSSL=falsespring.datasource.username=springbootspring.datasource.password=springboot# Hikari 数据源专用配置spring.datasource.hikari.maximum-pool-size=20spring.datasource.hikari.minimum-idle=5# JPA 相关配置spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialectspring.jpa.database=mysqlspring.jpa.show-sql=truespring.jpa.hibernate.ddl-auto=create
spring.jpa.show-sql=true 配置在日志中打印出执行的 SQL 语句信息。
spring.jpa.hibernate.ddl-auto=create 配置指明在程序启动的时候要删除并且创建实体类对应的表。这个参数很危险,因为他会把对应的表删除掉然后重建。所以千万不要在生成环境中使用。只有在测试环境中,一开始初始化数据库结构的时候才能使用一次。
spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect 。在 SrpingBoot 2.0 版本中,Hibernate 创建数据表的时候,默认的数据库存储引擎选择的是 MyISAM (之前好像是 InnoDB,这点比较诡异)。这个参数是在建表的时候,将默认的存储引擎切换为 InnoDB 用的。
建立一个数据实体类user
实现持久层服务UserDao
UserDao支持的方法如下:
新建单元测试方法
可以看到,我们所做的全部事情仅仅是在 SpingBoot 工程里面增加数据库配置信息,声明一个 UserDO 的数据库实体对象,然后声明了一个持久层的接口,改接口继承自 org.springframework.data.jpa.repository.JpaRepository 接口。然后,系统就自动拥有了丰富的增加、删除、修改、查询功能。查询功能甚至还拥有了排序和分页的功能。
运行单元测试方法
通过控制台日志发现 ,已经成功新建了user表并且插入了一条user数据
结语
这个样例基本上讲述了 JPA 使用过程中的一些细节。我们可以看出。使用 JPA 来完成关于关系数据库增删改查的功能是非常的方便快捷的。