
其实我是想给我给它写的 starter 骗一下星星→_→ illyasviel/elide-spring-boot
Elide 是一个主要基于 JPA 注释自动构建 JSON API / GraphQL 接口的中间件。只需要给实体对象新增一个注解即可获得 CRUD 的 API,同时也提供了接口让你整合业务逻辑,权限控制,swagger 文档...
类比的话,或许有点儿类似于 Spring Data REST,不过它做得更多,生成的接口也更丰富...
引入 starter 即可完成自动配置(Spring Boot 2)
<dependency> <groupId>org.illyasviel.elide</groupId> <artifactId>elide-spring-boot-starter</artifactId> <version>1.4.0</version> </dependency> 如果你需要 GraphQL 的接口,你需要额外引入
<dependency> <groupId>com.yahoo.elide</groupId> <artifactId>elide-graphql</artifactId> <version>${elide.version}</version> <!-- 目前 starter 指定版本为 4.2.3 --> </dependency> @Setter @NoArgsConstructor @Table(name = "users") @Entity @Include(rootLevel = true) // <---- 在你实体类上添加一行注解 public class User { private Integer id; private String username; private String password; @Id @GeneratedValue public Integer getId() { return id; } public String getUsername() { return username; } public String getPassword() { return password; } } P.S. 请注意你的 JPA 及下文所述的注解最好放在 get 方法上,Elide 目前没有完全支持位于 field 上的注解。
OK,完成了!!

你已经拥有了 CRUD 的 API 接口了,现在来试试吧。
使用 JSON API 创建 user
var data = { "data": { "type": "user", "attributes": { "username": "test", "password": "test" } } }; fetch('http://localhost:8080/api/user', { method: 'POST', headers: { 'Accept': 'application/vnd.api+json', 'Content-Type': 'application/vnd.api+json', }, body: JSON.stringify(data), }) .then(respOnse=> response.ok && response.json()) .then(json => console.log(json)); 使用 JSON API 分页 & 过滤 & 指定属性 & 排序查询 user
fetch(encodeURI("http://localhost:8080/api/user?filter[user]=username=='test'&fields[user]=id,username&sort=-id&page[number]=1&page[size]=3&page[totals]"), { method: 'GET', headers: { 'Accept': 'application/vnd.api+json', }, }) .then(respOnse=> response.ok && response.json()) .then(json => console.log(json)); var data = { "data": { "id": "1", "type": "user", "attributes": { "username": "new name" } } }; fetch('http://localhost:8080/api/user/1', { method: 'PATCH', headers: { 'Accept': 'application/vnd.api+json', 'Content-Type': 'application/vnd.api+json', }, body: JSON.stringify(data), }) .then(respOnse=> console.log(response.status === 204 ? 'ok' : 'failure')); fetch('http://localhost:8080/api/user/1', { method: 'DELETE', headers: { 'Accept': 'application/vnd.api+json', }, }) .then(respOnse=> console.log(response.status === 204 ? 'ok' : 'failure')); 感兴趣的话更多内容可以查看原文
我这算不算自来水,能不能领广告费?(~ ̄ ̄)~
1 zhuawadao 2018-07-27 09:29:12 +08:00 13 天了,都没有回复,心疼楼主!那我来一个吧 |