首页 > 解决方案 > 如何使用 Spring-Data-Rest 通过不可为空的连接列在单向关系中创建和链接子实体

问题描述

当它们之间的关系是一对多+单向(特别是从父级到子级)时,我无法弄清楚如何使用 Spring-Data-Rest 添加子实体(让我们说一个comment实体到父实体)post以及当数据库在子实体表上使用不可为空的连接列时。

对于使用 Spring-Data-Rest 链接关系中的两个实体,我相信通常的方法是首先创建两个实体(对它们各自的端点进行 POST 调用),然后用 PUT 或 PATCH 将它们链接到关系端点,例如作为/api/posts/1/comments. 该链接请求的正文将包含指向先前创建的子实体的链接,例如http://localhost:8080/api/comments/1. 但是,对于我在子实体上具有不可为空的连接列的情况,当我尝试创建子实体时,我无法创建子实体,因为它无法使用连接列的null值插入到数据库中。parent_id

@Entity
public class Post {
  @Id
  private Long id;

  private String title;

  @OneToMany
  @JoinColumn(name = "post_id", nullable = false)
  private List<Comment> comments;
}
@Entity
public class Comment {
  @Id
  private Long id;

  private String message;
}
@RepositoryRestResource
interface PostRestRepository implements JpaRepository<Post, Long> {}

@RepositoryRestResource
interface CommentRestRepository implements JpaRepository<Comment, Long> {}

尝试通过 POST 调用创建子实体时/api/comments,我在响应正文中收到此错误:ERROR: null value in column \"post_id\" violates not-null constraint

我假设在这种情况下有一种方法可以创建评论并将评论链接到帖子,但我无法在任何地方找到答案。

标签: spring-bootspring-data-jpaentity-relationshipspring-data-restjoincolumn

解决方案


您可以在创建新资源时发送现有Comment资源的 URI 数组作为字段的值,如下所示:commentsPost

POST /api/posts

{
  "title": "My Post",
  "comments": [
    "http://api-url/comments/1",
    "http://api-url/comments/2"
  ]
}

不幸的是,SDR 文档中似乎省略了这一重要信息。但是,您可以在源代码中找到它。

关于缺乏可追溯到 2017 年的文档存在一个未解决的问题。


推荐阅读