Spring Data项目的目的是为了简化构建基于Spring框架应用的数据访问技术,包括非关系数据库、Map-Reduce框架、云数据服务等等;另外也包含堆关系数据库的访问支持。
Spring Data包含多个子项目:
- Spring Data Commons
- Spring Data JPA
- Spring KeyValue
- Spring Data LDAP
- Spring Data MongoDB
- Spring Data REST
- Spring Data Redis
…等
1. Spring Data特点
Spring Data为我们提供使用统一的API来对数据访问层进行操作;这主要是Spring Data Commons项目来实现的。Spring Data Commons让我们在使用关系型或非关系型数据访问技术时都基于Spring提供的统一标准,标准包含了CRUD、查询、排序和分页的相关操作。
2.统一的Repository接口
3. JPA与Spring Data
1)JpaRepository基本功能
编写接口继承JpaRepository既有CRUD及分页等基本功能
2)定义符合规范的名字命名
在接口中只需要声明符合规范的方法,即拥有对应的功能
以下是部分关键字
关键字 | 方法命名 | 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 < ? |
GreaterThan | findByIdGreaterThan | where id > ? |
IsNull | findByNameIsNull | where name is null |
isNotNull,NotNull | findByNameNotNull | where name is not null |
Like | findByNameLike | where name like ? |
3)@Query自定义查询,定制查询sql
4)Specfications查询
4. Spring Data、Spring Data JPA, JPA的关系
5. Spring Data JPA例子
Reposity:
//继承JpaRepository来完成对数据库的操作
public interface UserReposity extends JpaRepository<User,Integer> {
List<User> getUserByIdGreaterThan(Integer id);
}
Entity:
//使用JPA注解配置映射关系
@Entity //告诉JPA这是一个实体类(和数据库映射的类)
@Table(name = "user") //来指定和那个数据表对应;如果省略默认表明就是user
public class User {
@Id //表明这是一个主键
@GeneratedValue(strategy = GenerationType.IDENTITY) //自增主键
private Integer id;
@Column(name = "last_name", length = 50) //这是和数据表对应的一个列, 如果不设置name属性的值,默认为列名
private String lastNme;
private String email;
...set/set...
}
配置:
spring:
datasource:
url: jdbc:mysql://localhost:3306/jpalearning?useUnicode=true&characterEncoding=UTF-8&serverTimezone=EST
username: root
password: root
driver-class-name: com.mysql.jdbc.Driver
jpa:
hibernate:
ddl-auto: update #更新或者创建数据表结构
show-sql: true #控制台显示sql
Controller:
@RestController
public class UserController {
@Autowired
UserReposity userReposity;
@GetMapping("/user/{id}"