[英]Save a Spring Data Rest JPA entity in a custom controller and return a HAL representation
在我的Spring Boot Web应用程序中,我有一个JPA实体Medium
,它记录有关上载文件的信息。
我有一个基本的Spring Data Rest存储库来处理一般操作:
@RepositoryRestResource(path = "/media")
public interface MediumRepository extends CrudRepository<Medium, Long> {
}
但是,我需要客户端使用HTTP分段上传来上传文件,然后创建一个Medium
记录并在响应中返回它。 响应的结构应该与调用repository.save()
相同。 我不知道是如何添加HATEOAS元数据的。 显然,如果我刚回来
return mediumRepository.save(medium);
它将返回实体的基本JSON表示形式,而不是HATEOAS。 我已经知道我可能应该使用PersistentEntityResourceAssembler
。
因此,我当前的控制器代码是:
@RestController
@RequestMapping("/upload")
public class MediaEndpoint {
@Autowired
private MediumRepository mediumRepository;
@RequestMapping(method = POST)
public PersistentEntityResource uploadMedium(
@RequestPart MultipartFile data,
PersistentEntityResourceAssembler persistentEntityResourceAssembler) {
Medium medium = new Medium();
// setup of the medium instance
Medium savedMedium = mediumRepository.save(medium);
return persistentEntityResourceAssembler.toResource(savedMedium);
}
}
但是,我无法将persistentEntityResourceAssembler
注入该方法中-我正在
Failed to instantiate [org.springframework.data.rest.webmvc.PersistentEntityResourceAssembler]: No default constructor found; nested exception is java.lang.NoSuchMethodException: org.springframework.data.rest.webmvc.PersistentEntityResourceAssembler.<init>()
我该如何实施?
尝试使用@RepositoryRestController而不是@RestController。
按照Cepr0的回答 ,我将控制器更改为@RepositoryRestController
,但出现异常
Circular view path [upload]: would dispatch back to the current handler URL [/upload] again.
Check your ViewResolver setup! (Hint: This may be the result of an unspecified view,
due to default view name generation.)
我发现 RepositoryRestController
没有用@ResponseBody
注释,并且应该返回ResponseEntity
,因此我将代码更改为以下内容:
@RepositoryRestController
@RequestMapping("/upload")
public class MediaEndpoint {
@Autowired
private MediumRepository mediumRepository;
@RequestMapping(method = POST)
public ResponseEntity<PersistentEntityResource> uploadMedium(
@RequestPart MultipartFile data,
PersistentEntityResourceAssembler persistentEntityResourceAssembler) {
Medium medium = new Medium();
// setup of the medium instance
Medium savedMedium = mediumRepository.save(medium);
return ResponseEntity.ok(persistentEntityResourceAssembler.toResource(savedMedium));
}
}
这为我提供了带有HATEOAS元数据的不错的JSON响应。
另外,用@ResponseBody
注释方法或控制器的方法也相同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.