【问题标题】:how to properly handle POST in a custom Spring Data Rest controller?如何在自定义 Spring Data Rest 控制器中正确处理 POST?
【发布时间】:2017-02-24 06:40:13
【问题描述】:

在我的 Spring Data Rest 应用程序中,我有一个标准存储库:

@RepositoryRestResource(collectionResourceRel = "people", path = "people")
public interface PersonRepository extends PagingAndSortingRepository<Person, Long> {

        List<Person> findByLastName(@Param("name") String name);

}

我还有一个自定义控制器,它将在 HTTP POST 上实现一些额外的逻辑:

@RestController
@RequestMapping("/people")
public class PersonController {
    @RequestMapping(value = "/**", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<String> savePerson(@RequestBody Person person, UriComponentsBuilder b, @RequestParam Map<String, ?> id) {


        UriComponents uriComponents = 
                b.path("/people/").buildAndExpand();
        HttpHeaders responseHeaders = new HttpHeaders();
           responseHeaders.setLocation(uriComponents.toUri());
           responseHeaders.set("MyResponseHeader", "MyValue");
        return new ResponseEntity<String>("Hello World\n\n", responseHeaders, HttpStatus.CREATED);
    }
}

由于我没有明确使用 Hibernate Entity Manager,因此在此控制器中保存“Person”实体的正确方法是什么? “person”参数只是一个 POJO,所以它没有任何持久化 CRUD 方法。

【问题讨论】:

    标签: java spring spring-data-rest


    【解决方案1】:

    如果 PersonRepository 中使用的 Person 类与您在控制器中使用的将 RequestBody 映射到的任何类相同,那么在控制器方法中您只需执行 personRepository.save(person) -- 假设 personRepository 是一个 Autowired 实例PersonRepository 类。

    我猜,您正在尝试使用 spring data rest https://spring.io/guides/gs/accessing-data-rest/ 。如果是这种情况,您的类路径中可能有内存数据库 com.h2database:h2。这就是为什么在给定的示例中,即使没有配置数据库或将任何 JPA 注释添加到您的 person 类,一切都可以正常工作。因此,您仍然可以从您的自定义控制器执行 personRepository.save(person),而无需在您的 Person 类中使用任何 JPA 注释。

    【讨论】:

      猜你喜欢
      • 2016-02-07
      • 2015-12-07
      • 2016-08-20
      • 2016-01-27
      • 2015-03-08
      • 1970-01-01
      • 2015-12-31
      • 2017-11-28
      • 2017-08-15
      相关资源
      最近更新 更多