`
Adan-Chiu
  • 浏览: 20000 次
社区版块
存档分类
最新评论

Spring Data REST 快速构建 restful api 应用

 
阅读更多

      

Spring Data REST

       Spring Data REST基于Spring Data的repository之上并自动将其导出为REST资源。目前Spring Data REST支持Spring Data JPA、Spring Data MongoDB、Spring Data Neo4j、Spring Data GemFire、Spring Data Cassandra的 repository 自动转换成REST服务。简单点说,Spring Data REST把我们需要编写的大量REST模版接口做了自动化实现.

 

      利用spring boot + spring-data-rest + spring-data-jpa实现基本的增删改查api

dependencies {
    compile 'com.alibaba:druid:1.1.17'
    compile 'org.springframework.boot:spring-boot-starter-data-jpa'
    compile 'org.springframework.boot:spring-boot-starter-data-rest'
    developmentOnly 'org.springframework.boot:spring-boot-devtools'
    runtimeOnly 'mysql:mysql-connector-java'
}

 配置spring boot

server.port = 80

spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name = com.mysql.cj.jdbc.Driver
spring.datasource.url = jdbc:mysql://192.168.134.128:3306/db_book?serverTimezone=CTT&useSSL=false&useUnicode=true&characterEncoding=UTF-8&allowPublicKeyRetrieval=true
spring.datasource.username = root
spring.datasource.password = 

spring.jpa.database=mysql
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.database-platform=org.hibernate.dialect.MySQL8Dialect

 创建Book实体类:

package com.wise.tiger.domain;

import javax.persistence.*;
import java.time.LocalDate;

@Entity
@Table(name = "tb_book")
public class Book {
    /**
     * id
     */
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    /**
     * 图书名称
     */
    @Column(length = 12,nullable = false)
    private String title;
    /**
     * 图书作者
     */
    @Column(length = 12)
    private String author;
    /**
     * 图书价格
     */
    private float price;
    /**
     * 出版社信息
     */
    @Column(length = 25)
    private String publisher;
    /**
     * 图书简介
     */
    @Lob
    private String intro;
    /**
     * 出版日期
     */
    private LocalDate publishDate = LocalDate.now();
// ******************setter and getter**********//
}

 创建BookRepository接口

package com.wise.tiger.repository;

import com.wise.tiger.domain.Book;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;

@RepositoryRestResource(path = "book")
public interface BookRepository extends JpaRepository<Book,Integer> {
}

      在Repository接口上添加@RepositoryRestResource注解,并添加了一个Path为book。这样即可实现Book实体类的RESTFul风格的所有(基于Repository接口定义的api)接口。没有service层也没有Controller。

启动项目spring boot进行测试

测试

  • 发现服务:http://localhost:80/


     
    "http://localhost/book{?page,size,sort}"为资源路径,其中page,size,sort为分页排序参数
  • 以GET方式请求所有资源列表http://localhost/book发现book列表为空

     
  • 以POST方式请求资源:http://localhost/book,提交json数据作为参数(可接收application/hal+json或application/json类型数据)添加一本图书信息


    可以继续多添加几本图书后再次以GET方式请求 
  • PUT方式请求修改图书信息
  • DELETE请求删除图书信息:http://localhost/book/2
  • 分页和排序
    分页参数:

    page:当前页,从0开始,默认值0

    size:每页显示记录数,默认值20

    可通过参数指定:http://localhost/book/?page=1&size=5

    排序参数
    sort
    格式:http://localhost/book/?page=1&size=5&sort=title,desc
    其中title为排序属性名称,desc为降序,升序为asc
           要在自己的查询方法中使用分页,需要更改方法签名以接受其他可分页参数,并返回一个页面而不是列表。例如,以下查询方法导出到/book/search/titleStartsWith并支持分页:
    @RestResource(path = "titleStartsWith", rel = "titleStartsWith")
    Page findByTitleStartsWith(@Param("title") String title, Pageable p);
  • 自定义Controller
     到目前为止,我们只写了很少的代码,只写了repository(DAO),但是却已经实现了增删改查REST api。我们甚至连 controller都没有写,就访问了这么多的REST url。
      我们只通过@RepositoryRestResource(path = "book")在 repository中就能够把 /path路径暴露出来。便一切都有了,这就是spring-data-rest的魔力。上面我们所访问的 /book/* 的地址,是从repository中通过 @RepositoryRestResource 注解暴露出去的,现在我们写一个自己的Controller来暴露额外的REST资源,访问路径/book/search/listBooks
@RepositoryRestController
@RequestMapping("/book")
public class PersonController {

    @RequestMapping(method = GET, value ="/search/listBooks")
    public String list(){
        return "查询得到符合要求全部图书信息,实际去repository中查 ";
    }
}
 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics