@RepositoryRestResource使用

作用:设置rest请求路径。通过匹配路径中的参数完成对数据库的访问。配合JPA使用

 

案例:

  (1)配置文件中指定基路径

#配置rest请求方式的基路径
spring.data.rest.base-path=/api

  (2)创建pojo:使用@entity注解,使用略。

  (3)自定义PerosnRepository,创建数据表访问接口:需要借助步骤2的pojo,需要实现JpaRepository接口。

 

code:

 1 /*
 2 配置Person的访问接口
 3 @RepositoryRestResource作用:在rest类型的请求路径中自动截取people参数
 4     补充;Spring Data REST的JSON输出格式使用的是HAL格式。
 5  */
 6 @RepositoryRestResource(path = "people")
 7 public interface PerosnRepository extends JpaRepository<Person,Long> {
 8 
 9     @RestResource(path = "nameStartsWith",rel = "nameStartsWith")
10     List<Person> findByNameStartsWith(@Param("name") String name);
11 }

  (4)直接插入数据,在controlle中使用rest的参数匹配完成数据插入。

 1  /**
 2      * 请求参数:http://localhost:8080/save/%E6%9D%A8%E6%B6%A6%E6%98%A5/18/%E9%87%8D%E5%BA%86
 3      * @param name
 4      * @param age
 5      * @param address
 6      */
 7     @RequestMapping(value = "/save/{name}/{age}/{address}")
 8     public void save(@PathVariable String name, @PathVariable int age, @PathVariable String address){
 9         perosnRepository.save(new Person(6l,name,age,address));
10     }

 

posted @ 2020-06-04 15:28  怪兽不纯粹  阅读(3444)  评论(0)    收藏  举报