【问题标题】:How to update bidirectional @ManyToOne/@OneToMany relationship via REST from the inverse side如何通过 REST 从反向更新双向 @ManyToOne/@OneToMany 关系
【发布时间】:2015-06-06 09:37:17
【问题描述】:

我在 Spring Data Rest 应用中有 2 个实体:

@Entity
public class Question {
    ...
    @OneToMany(mappedBy = "question")
    private Set<Answer> answers = new HashSet<>();
    ...
}

@Entity
public class Answer {
    ...
    @ManyToOne
    Question question;
    ...
}

两个实体的 Spring Data 存储库:

@RepositoryRestResource
public interface QuestionRepository extends      PagingAndSortingRepository<Question, Long> {
}

@RepositoryRestResource
public interface AnswerRepository extends PagingAndSortingRepository<Answer,     Long> {

}

假设我有一个 ID 为 1 的问题和两个 ID 为 1 和 2 的答案。 然后我可以像这样链接它们:

curl -v -X PUT -H "Content-Type: text/uri-list" -d "http://localhost:8080/questions/1" http://localhost:8080/answers/1/question
curl -v -X PUT -H "Content-Type: text/uri-list" -d "http://localhost:8080/questions/1" http://localhost:8080/answers/2/question

但不是这样:

curl -v -X PUT -H "Content-Type:text/uri-list" -d $'http://localhost:8080/answers/1\nhttp://localhost:8080/answers/2' http://localhost:8080/questions/1/answers

Spring Data Rest 通过获取 ID 为 1 的 Question 实例来处理最后一个 curl 请求,将两个答案添加到其集合中并在 Question 上调用休眠合并。

问题在于更改被忽略,因为它们是从反向(不是关系的所有者)方面进行的。据我所知,您无法更改所有者或使其在休眠中以一对多/多对一关系从双方更新。

这是否意味着我必须逐一更新答案集? 是否可以配置 Spring Data Rest 以便它从所有者端更新关系以便它被休眠持久化?

【问题讨论】:

  • JPA 中的关系始终是单向的,除非您在两个方向上将父级与子级关联起来。
  • 你能发布更具体的你想要什么吗?
  • 你不应该在@OneToMany注解中添加cascade属性吗?
  • 我的关系是双向的——答案中有问题的引用,问题中也有答案的引用。
  • 一般的级联实现(任何类型的 org.hibernate.annotations.Cascade 或 javax.persistence.CascadeType)只有在实体已经被链接之后才会做任何事情,如果我没记错的话。

标签: spring spring-data-jpa spring-data-rest


【解决方案1】:

我是 Spring Data Rest 的新手。Spring Data Rest 不这样做的原因(我认为)如下:

一个对象的 PUT 请求意味着它应该被更新以拥有你给它的东西(例如问题的两个答案)。但是,如果您稍后决定在 uri 列表中放置两个不同的 Answer 对象,那么前两个 Answer 对象应该指向哪里?他们应该设置为 Null 吗?如果您的模型在 Answer 实体中的问题字段中使用 @NotNull 怎么办?

总而言之,更新答案以指向不同的问题是明确定义的,但更新问题的答案列表并没有那么明确,因此 Spring Data Rest 避免了这种情况。这当然是一个估计的猜测,我没有看过 Spring Data Rest 背后的代码

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-12
    • 2023-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-17
    • 1970-01-01
    • 2019-05-21
    相关资源
    最近更新 更多