在自定义控制器中保存 Spring Data Rest JPA 实体和 return HAL 表示

Save a Spring Data Rest JPA entity in a custom controller and return a HAL representation

在我的 Spring 引导 Web 应用程序中,我有一个 JPA 实体 Medium 记录有关上传文件的信息。

我有一个基本的 Spring Data Rest 存储库来处理一般操作:

@RepositoryRestResource(path = "/media")
public interface MediumRepository extends CrudRepository<Medium, Long> {
}

但是,我需要客户端使用 HTTP 分段上传来上传文件,然后创建一个 Medium 记录并在响应中 return 它。响应的结构应与调用 repository.save() 相同。我想不通的是如何添加 HATEOAS 元数据。显然,如果我只是 return

return mediumRepository.save(medium);

它将 return 实体的基本 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。

之后,我将我的控制器更改为 @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 注释并且应该 return 一个 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));
    }
}

这给了我一个很好的 JSON 响应与 HATEOAS 元数据。

或者,使用 @ResponseBody 注释方法或控制器的工作方式相同。