【问题标题】:PUT on ManyToMany association in Spring Data Rest在 Spring Data Rest 中放置多对多关联
【发布时间】:2020-03-12 10:23:07
【问题描述】:

我正在尝试弄清楚如何将 PUT 直接放在我拥有的多对多关联上。

我的实体示例(更改名称以增加混淆):

第一个实体:

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

    private String name;

    @OneToMany(mappedBy = "first")
    private Set<Third> thirds = new HashSet<>();
}

第二个实体:

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

    private String name;

    @OneToMany(mappedBy = "second")
    private Set<Third> thirds = new HashSet<>();
}

第三实体:

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

    private String type;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "first_id")
    private First first;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "second_id")
    private Second second;
}

现在我想做的是这样的:

PUT /first/1/thirds
{
    "second": "/second/1",
    "type": "TEST"
}

但是什么也没发生。当您在多对多中间使用实体时,是否可以通过这种方式放置关联?还是应该直接将关联发布到 /third?

【问题讨论】:

  • 您使用的是 spring-rest-data 还是自定义控制器?
  • 我正在使用带有 @RepositoryRestResource 注释的存储库

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


【解决方案1】:

您首先必须创建一个 First 实例,如下所示:

curl -i -X POST -d "{\"name\":\"first\"}"
  -H "Content-Type:application/json" http://localhost:8080/firsts

那么你必须创建第三个实例:

curl -i -X POST -H "Content-Type:application/json"
  -d '{\"type\":\"third\"}' http://localhost:8080/thirds

最终,您可以创建与 PUT 的关联:

curl -i -X PUT -H "Content-Type:text/uri-list"
-d "http://localhost:8080/firsts/1" http://localhost:8080/thirds/1/first

【讨论】:

  • 我明白了,所以不能将 Third 的实例直接添加到 First 或 Seconds 关联集?
  • 我不确定这是不可能的,但我做不到,如果我尝试 -:(
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-03-27
  • 2014-03-18
  • 2019-01-29
  • 1970-01-01
  • 2018-10-08
  • 2021-10-26
  • 1970-01-01
相关资源
最近更新 更多