除了常见的方式实现 RESTful API,还有一种简单的方式实现 RESTful API,那就是用 JPA 方式。首先介绍一下 JPA,它是 Sun 公司推荐的 JAVA 持久化规范,为了简化 ORM 技术而产生。需要注意的是,他只是一套规范,不是一套具体的框架,只要符合这个规范的框架都可以被称为 JPA 框架。其中 Spring Boot 也有封装好的 spring-boot-start-data-jpa。
新建项目jpatest,对于 JPA 的安装也是在 pom.xml 中添加依赖,同时也加入数据库相关依赖:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>org.example</groupId><artifactId>jpatest</artifactId><version>1.0-SNAPSHOT</version><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.1.8.RELEASE</version><relativePath/></parent><properties><maven.compiler.source>8</maven.compiler.source><maven.compiler.target>8</maven.compiler.target><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties><dependencies><dependency><!-- json--><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-json</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency><dependency><groupId>org.springframework.data</groupId><artifactId>spring-data-rest-webmvc</artifactId></dependency><dependency><groupId>org.springframework.data</groupId><artifactId>spring-data-jpa</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId></dependency><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.1.23</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.28</version></dependency></dependencies></project>
然后配置数据库配置和 druid 连接池配置,编写 application.yml 代码如下:
spring:datasource:url: jdbc:mysql://localhost:3306/spring_boot?useTimezone=true&serverTimezone=UTCtype: com.alibaba.druid.pool.DruidDataSourceusername: rootpassword: 123456driver-class-name: com.mysql.cj.jdbc.Driverjpa:database: mysqlshow-sql: true #打印sql语句,只在测试阶段hibernate:ddl-auto: none #是否自动创建表
创建实体类,创建Dao层文件夹,编写 Book.java作为实体类,代码如下:
package org.example.dao;import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
//实体类对应的数据库表名
@Entity(name = "my_comic_books")
public class Book {//主键字段,实体类唯一标识@Id//指定如何为数据库表中的主键字段生成唯一的值,自增@GeneratedValue(strategy = GenerationType.IDENTITY)private Integer id;private String name;private String author;private float price;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getAuthor() {return author;}public void setAuthor(String author) {this.author = author;}public float getPrice() {return price;}public void setPrice(float price) {this.price = price;}
}
创建一个接口 ComicBookRepository,代码如下:
import org.example.dao.Book;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
import org.springframework.stereotype.Repository;
//替换掉默认路由名称
@RepositoryRestResource(path = "mybook")
public interface ComicBookResitory extends JpaRepository<Book,Integer> {
}
该接口默认继承 JpaRepository 中的方法,常用方法如下:
public interface JpaRepository<T, ID> extends PagingAndSortingRepository<T, ID>, QueryByExampleExecutor<T> {List<T> findAll();List<T> findAll(Sort var1);List<T> findAllById(Iterable<ID> var1);<S extends T> List<S> saveAll(Iterable<S> var1);void flush();<S extends T> S saveAndFlush(S var1);void deleteInBatch(Iterable<T> var1);void deleteAllInBatch();T getOne(ID var1);<S extends T> List<S> findAll(Example<S> var1);<S extends T> List<S> findAll(Example<S> var1, Sort var2);
}
直接访问,不需要编写 Controller 层。
chu
除此之外,还可以增加其他配置,例如分页数,排序方式,是否增加请求前缀等,配置如下:
data:rest:#设置每页记录数default-page-size: 2#分页页码参数名page-param-name: page#分页查询记录参数名limit-param-name: size#分页查询排序参数sort-param-name: sort#请求路径前缀base-path:
除了写在文件中,还可以写在代码当中,只需编写一个类实现 RepositoryRestConfigurer 接口,
package org.example.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.rest.core.config.RepositoryRestConfiguration;
import org.springframework.data.rest.webmvc.config.RepositoryRestConfigurer;
@Configuration
public class MyRestConfig implements RepositoryRestConfigurer {@Overridepublic void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {config.setPageParamName("page").setLimitParamName("size").setSortParamName("sort").setDefaultPageSize(2).setBasePath("").setReturnBodyOnCreate(true);}
}
代码的优先级高于文件,如果有这个文件,那么以这个文件的设置为准。