SpringData
简介
Spring Data是一个用于简化数据库访问,并支持云服务的开源框架,是hibernate的封装。其主要目标是使得对数据的访问变得方便快捷。
可以极大的简化JPA的写法,可以在几乎不用写实现的情况下(即不用写具体的查询语句),实现对数据的访问和操作。除了CRUD外,还包括如分页、排序等一些常用的功能。
Spring Data JPA接口
Spring Data JPA提供了6个接口
- Repository
- CrudRepository
- PagingAndSortingRepository
- JpaRepository
- JpaSpecificationExecutor
- Specification
下面逐个介绍接口
Repository
最顶层的接口,是一个空的接口,目的是为了统一所有Repository的类型,且能让组件扫描的时候自动识别
CrudRepository
是Repository的子接口,提供CRUD的功能
PagingAndSortingRepository
是CrudRepository的子接口,添加分页和排序的功能
JpaRepository
是PagingAndSortingRepository的子接口,增加了一些实用的功能,比如:批量操作等
JpaSpecificationExecutor
用来做负责查询的接口
Specification
是Spring Data JPA提供的一个查询规范,要做复杂的查询,只需围绕这个规范来设置查询条件即可
Spring Data支持的数据库
Spring Data支持的关系型存储技术:
- JDBC
- JPA
Spring Data支持的NoSQL存储技术:
- Hbase(列存储数据库)
- MongoDB(文档存储数据库)
- Redis(key-value数据库)
- Neo4j(图数据库)
Spring Data Repository 查询方法定义规范
使用Spring Data Repository进行查询时,只需要按照要求写查询方法即可,不需要写详细的查询语句
- 查询方法以 find | read | get 开头
- 涉及条件查询时,条件的属性用条件关键字连接
- 条件属性以首字母大写
方法定义规范
关键字 | 方法命名 | 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 | where id > ? |
Before | findByIdBefore | where id < ? |
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(?) |