Spring Data 项目的目的是为了简化基于 Spring 框架应用的数据访问技术,包括非关系数据库、Map-Reduce 框架、云数据服务等等;另外也包含对关系数据库的访问支持。
SpringData为我们提供使用统一的API,用来对数据访问层进行操作;这主要是Spring Data Commons项目来实现的。Spring Data Commons让我们在使用关系型或者非关系型数据访问技术时都基于Spring提供的统一标准,标准包含了CRUD(创建、获取、更新、删除)、排序和分页的相关操作。
MongoDB(文档数据库)
Neo4j(图形数据库)
Redis(键值存储)
HBase(列族数据库)
JDBC
JPA
Spring Data JPA 致力于减少数据访问层(dao层)的开发量,开发者唯一要做的,就只是声明持久层的接口,其他都交由Spring Data JPA来帮我们完成。
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-data-jpaartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-jdbcartifactId>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<scope>runtimescope>
dependency>
create database if not exists jpa;
spring:
datasource:
username: root
password: 123456
url: jdbc:mysql://192.168.0.110:3306/jpa?serverTimezone=GMT%2B8
driver-class-name: com.mysql.cj.jdbc.Driver
编写一个实体类(bean)和数据表进行映射,并且配置好映射关系
package com.ty.entity;
import javax.persistence.*;
@Entity
@Table(name="student_info") //不设置name值,默认name的值为:类名
public class StudentInfo {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)//设置主键生成策略
private Integer id;
@Column //默认列名和属性名称一致
private String stuName;
@Column(name = "stu_no")
private String stuNo;
}
package com.ty.dao;
import com.ty.entity.StudentInfo;
import org.springframework.data.jpa.repository.JpaRepository;
//继承JpaRepository来完成对数据库的操作
public interface StudentDao extends JpaRepository<StudentInfo,Integer> {
}
通过JpaProperties类中属性进行设置。
spring:
jpa:
show-sql: true
hibernate:
ddl-auto: update
package com.ty.controller;
import com.ty.dao.StudentDao;
import com.ty.entity.StudentInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class StudentController {
@Autowired
StudentDao studentDao;
@GetMapping("/student/{id}")
public StudentInfo getStudentById(@PathVariable("id") int id){
StudentInfo one = studentDao.getOne(id);
return one;
}
@GetMapping("/student")
public StudentInfo addStudent(StudentInfo studentInfo){
studentDao.save(studentInfo);
return studentInfo;
}
}
直接调用Dao接口的父类JPA接口的分页方法
Page<StudentInfo > findAll(int page, int pagesize);
public Page<StudentInfo > findAll(int page, int pagesize) {
Pageable pageable = PageRequest.of(page,pagesize);
return studentDao.findAll(pageable);
}
@GetMapping("/findAll")
public Page<StudentInfo> findAll(Integer page, Integer pageSize, HttpServletResponse response){
//解决跨域请求
response.setHeader("Access-Control-Allow-Origin","*");
if(page==null||page<=0){
page = 0;
}else {
page -= 1;
}
return studentService.findAll(page,pageSize);
}