【问题标题】:Spring data rest override nested property POST handlerSpring数据休息覆盖嵌套属性POST处理程序
【发布时间】:2017-05-21 13:48:48
【问题描述】:

我有一个 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 为 documentsproject 子资源生成的 CRUD 方法。

【问题讨论】:

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


    【解决方案1】:

    试试这样的:

    @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

    【讨论】:

      猜你喜欢
      • 2017-05-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-28
      • 2021-09-10
      相关资源
      最近更新 更多