当前位置: 首页 > 面试题库 >

在Spring Data REST中发布@OneToMany子资源关联

龙景澄
2023-03-14
问题内容

目前,我有一个使用Spring Data REST的Spring Boot应用程序。我有一个域实体Post,它@OneToMany与另一个域实体有关系Comment。这些类的结构如下:

Post.java:

@Entity
public class Post {

    @Id
    @GeneratedValue
    private long id;
    private String author;
    private String content;
    private String title;

    @OneToMany
    private List<Comment> comments;

    // Standard getters and setters...
}

Comment.java:

@Entity
public class Comment {

    @Id
    @GeneratedValue
    private long id;
    private String author;
    private String content;

    @ManyToOne
    private Post post;

    // Standard getters and setters...
}

他们的Spring Data REST JPA存储库是以下各项的基本实现CrudRepository:

PostRepository.java:

public interface PostRepository extends CrudRepository<Post, Long> { }

CommentRepository.java:

public interface CommentRepository extends CrudRepository<Comment, Long> { }

应用程序入口点是一个标准的,简单的Spring Boot应用程序。一切都已配置库存。

应用程序

@Configuration
@EnableJpaRepositories
@Import(RepositoryRestMvcConfiguration.class)
@EnableAutoConfiguration
public class Application {

    public static void main(final String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

一切似乎正常工作。当我运行该应用程序时,一切似乎都可以正常工作。我可以发布一个新的Post对象,http://localhost:8080/posts就像这样:

过程: {"author":"testAuthor", "title":"test", "content":"hello world"}

结果http://localhost:8080/posts/1:

{
    "author": "testAuthor",
    "content": "hello world",
    "title": "test",
    "_links": {
        "self": {
            "href": "http://localhost:8080/posts/1"
        },
        "comments": {
            "href": "http://localhost:8080/posts/1/comments"
        }
    }
}

但是,当我在GET处执行操作时,http://localhost:8080/posts/1/comments会{}返回一个空对象,并且如果我尝试对相同的URI发表评论,则会收到HTTP 405方法不允许。

创建Comment资源并将其与此关联的正确方法是什么Post?http://localhost:8080/comments如果可能,我想避免直接过帐。


问题答案:

应该像下面这样:

http://{server:port}/comment METHOD:POST

{"author":"abc","content":"PQROHSFHFSHOFSHOSF", "post":"http://{server:port}/post/1"}


 类似资料:
  • 他们的Spring Data REST JPA存储库是的基本实现: postrepository.java: commentrepository.java: 一切似乎都正常工作。当我运行应用程序时,一切看起来都正常工作。我可以将一个新的POST对象发布到,如下所示: 正文: 中的结果: 创建资源并将其与此相关联的正确方法是什么?如果可能的话,我希望避免直接发布到。

  • 有时我会看到这样的警告: 如果我重写或不重写布局资源会发生什么?

  • 本章呈现 JAX-RS 核心概念-资源和子资源的概述。 JAX-RS 2.0 的 JavaDoc 文档 可以在这里 找到。 JAX-RS 2.0 规范草案可以在这里 找到。

  • 我需要在REST API中实现子资源 URL将像: https://localhost:8080/v1/student/{id}? include=地址,资格,登录 因此,地址、资格和登录是三个子资源,如果我们添加这是查询参数,则将包括这三个子资源。子资源可以是对其他服务的数据库调用或rest调用 这个问题发生在实现端,我已经将@RequestParam列表包括在内 所以现在我在服务课上就是这样写

  • 随着 Jekyll 被更广泛的使用,一系列的教程、框架、扩展、示例和其他各种有用的资源也相继出现。下面列出了一些最流行的 Jekyll 资源合辑的链接。 Jekyll 提示和技巧,以及示例 与 GitHub Pages 集成的技巧 重用代码并保持文档同步至最新的示例。 使用 Simple Form 来集成一个简单的联系表单 JekyllBootstrap.com 提供了详细的解释,例子和辅助代码让