Spring数据休息覆盖嵌套属性POST处理程序

时间:2017-05-21 13:48:49

标签: java spring spring-boot spring-data spring-data-rest

我有一个Spring Data Rest存储库

public interface ProjectRepository extends CrudRepository<Project, Integer> {}

以下实体:

@javax.persistence.Entity
@Table(name = "project", uniqueConstraints = {@UniqueConstraint(columnNames = {"owner_id", "title"})})
public class Project {

    @Id
    @Column(name = "project_id")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;

    ...

    @ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @JoinTable(name = "project_document", joinColumns = {
            @JoinColumn(name = "project_id", nullable = false, updatable = false) },
            inverseJoinColumns = { @JoinColumn(name = "document_id",
                    nullable = false, updatable = false) })
    private Set<Document> documents;

    ...
}

我想覆盖嵌套documents集合的POST处理程序,并遵循recommended approach

@RepositoryRestController
public class DocumentController {


    @RequestMapping(value = "/projects/{projectId}/documents", method = RequestMethod.POST)
    public Document postDocument(
            final @PathVariable int projectId,
            final @RequestPart("file") MultipartFile documentFile,
            final @RequestPart("description") String description
    ) throws IOException {
        ...
    }
}

但是当我启动嵌套的POST时,它仍然使用原始的Spring生成的POST处理程序并抛出不支持的媒体类型错误。

当我将@RepositoryRestController更改为@RestController时,会使用正确的POST处理程序,但不会导出Spring为documents project子资源生成的CRUD方法。

1 个答案:

答案 0 :(得分:0)

尝试这样的事情:

@RequiredArgsConstructor
@RepositoryRestController
@RequestMapping("/projects/{id}")
public class ProjectsController {

    private final @NonNull DocumentRepository documentRepository;

    @PostMapping("/documents")
    public ResponseEntity<?> postDocument(@PathVariable("id") Project project, @RequestBody Document document) {
        if (project == null) {
            throw new Exception("Project is not found!");
        }

        if (document == null) {
            throw new Exception("Document is not found");
        }

        Document savedDocument = documentRepository.save(document.setProject(project));
        return new ResponseEntity<>(new Resource<>(savedDocument), CREATED);
    }
}

工作example