简体   繁体   English

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

[英]Spring data rest override nested property POST handler

I have a Spring Data Rest repository 我有一个Spring Data Rest存储库

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

for the following entity: 对于以下实体:

@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;

    ...
}

I want to override the POST handler of the nested documents collection and am following the recommended approach . 我想覆盖嵌套documents集合的POST处理程序,并遵循建议的方法

@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 {
        ...
    }
}

But when I fire up the nested POST, it still uses the original Spring generated POST handler and throws unsupported media-type error. 但是当我启动嵌套的POST时,它仍然使用原始的Spring生成的POST处理程序并抛出不支持的媒体类型错误。

When I change @RepositoryRestController to @RestController , the correct POST handler is used, but the Spring generated CRUD methods for documents subresource of project are not exported. 当我改变@RepositoryRestController@RestController ,正确的POST处理程序使用,但对于弹簧产生的CRUD方法documents的子资源project不会被导出。

Try something like this: 尝试这样的事情:

@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);
    }
}

Working example . 工作实例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM