一、Spring Data Jpa 简介
1.JPA
2.Spring Data Jpa
3.Jpa、Hibernate、Spring Data Jpa三者之间的关系
二、入门案例
1.增删改查
2.标准查询
JPA(Java Persistence API)意即Java持久化API,是Sun官方在JDK5.0后提出的Java持久化规范(JSR 338,这些接口所在包为javax.persistence,详细内容可参考:https://github.com/javaee/jpa-spec)
JPA的出现主要是为了简化持久层开发以及整合ORM技术,结束Hibernate、TopLink、JDO等ORM框架各自为营的局面。JPA是在吸收现有ORM框架的基础上发展而来,易于使用,伸缩性强。总的来说,JPA包括以下3方面的技术:
ORM映射元数据: 支持XML和注解两种元数据的形式,元数据描述对象和表之间的映射关系
API: 操作实体对象来执行CRUD操作
查询语言: 通过面向对象而非面向数据库的查询语言(JPQL)查询数据,避免程序的SQL语句紧密耦合
JPA架构

https://spring.io/projects/spring-data-jpa#overview
Spring Data Jpa官方解释
Spring Data JPA是Spring Data家族的一部分,可以轻松实现基于JPA的存储库。 此模块处理对基于JPA的数据访问层的增强支持。 它使构建使用数据访问技术的Spring驱动应用程序变得更加容易。
在相当长的一段时间内,实现应用程序的数据访问层一直很麻烦。 必须编写太多样板代码来执行简单查询以及执行分页和审计。 Spring Data JPA旨在通过减少实际需要的工作量来显著改善数据访问层的实现。 作为开发人员,您编写repository接口,包括自定义查找器方法,Spring将自动提供实现。
Spring Data生态
JPA是ORM规范,Hibernate、TopLink等是JPA规范的具体实现,这样的好处是开发者可以面向JPA规范进行持久层的开发,而底层的实现则是可以切换的。Spring Data Jpa则是在JPA之上添加另一层抽象(Repository层的实现),极大地简化持久层开发及ORM框架切换的成本。
Jpa、Hibernate、Spring Data Jpa三者之间的关系
项目结构
build.gradle
user.sql
配置spring相关
数据源信息
jpa的实现方式
配置要用到的实体类
配置jpa实现方的配置信息
配置事务管理器
声明式事务
spring_data_jpa.xml
User.java
@Query
value:数据库操作语句
nativeQuery:是否是原生查询,默认false,即默认使用jpql查询
@Modifying:声明当前是一个更新操作,需要修改数据库数据。
只能用于void或int/Integer的返回类型
因为需要修改数据库数据,未防止修改失败造成未知后果,需要搭配事务管理来是使用
@Transactional:添加事务管理支持
一般需要设置rollbackFor或者noRollbackFor,来表示什么情况下进行事务回滚
@Rollback:是否可以回滚,默认true
方法命名规则查询
spring data jpa制定了一些约定,如果按照这些约定来定义方法名,则会自动解析出sql语句。
findBy + 属性名 + 查询方式 + (And|Or) + 属性名 + 查询方式…
查询方式
方法命名
sql where字句
And
findByNameAndPwd
where name= ? and pwd =?
Or
findByNameOrSex
where name= ? or sex=?
Is,Equals
findById,findByIdEquals
where id= ?
Between
findByIdBetween
where id between ? and ?
LessThan
findByIdLessThan
where id < ?
LessThanEquals
findByIdLessThanEquals
where id <= ?
GreaterThan
findByIdGreaterThan
where id > ?
GreaterThanEquals
findByIdGreaterThanEquals
where id > = ?
After
findByIdAfter
Before
findByIdBefore
IsNull
findByNameIsNull
where name is null
isNotNull,NotNull
findByNameNotNull
where name is not null
Like
findByNameLike
where name like ?
NotLike
findByNameNotLike
where name not like ?
StartingWith
findByNameStartingWith
where name like ‘?%’
EndingWith
findByNameEndingWith
where name like ‘%?’
Containing
findByNameContaining
where name like ‘%?%’
OrderBy
findByIdOrderByXDesc
where id=? order by x desc
Not
findByNameNot
where name <> ?
In
findByIdIn(Collection<?> c)
where id in (?)
NotIn
findByIdNotIn(Collection<?> c)
where id not in (?)
True
findByAaaTue
where aaa = true
False
findByAaaFalse
where aaa = false
IgnoreCase
findByNameIgnoreCase
where UPPER(name)=UPPER(?)
UserDao.java
CURDTest.java
这里是JpaSpecificationExecuto的源码,为了便于阅读,我删除了注释,有的方法已经在上面的代码中演示过。可以看到,这5个方法有个共同点,接收一个Specification参数。
Specification是对JPA规范中Root、CriteriaQuery、CriteriaBuilder的一层封装,用于构建过滤条件。实例化Specification需要实现它的toPerdicate方法
这里介绍一个例子,查询表中年龄大于18的湖北人
SpecificationTest.java